I am developing using asp.net/c# and when trying to type this code: FileUpload1.SaveAs(inpemphasized textut_image) this._Encrypt(input_image, output_image);

I faced a problem that is: 'Encrypt' does not contain a definition for 'Encrypt' and no extension method 'Encrypt' accepting a first argument of type 'Encrypt' could be found (are you missing a using directive or an assembly reference?)

What I tried to do for solving this problem: FileUpload1.SaveAs(input_image); this._Encrypt(input_image, output_image); private void _Encrypt(string input_image, string output_image) { throw new NotImplementedException(); }

and suddenly the error was removed! Is that solution right? Thanks in advance...

Want to make a windows billing system with the help of Asp.net c£ and sql server 2012. How to start the project as I am a very fresher in web development?


    public class Store
    {
        [Key]
        [Display(Name = "Id")]
        public int StoreId { get; set; }

        [Required]
        [Display(Name = "Address")]
        public int AddressId { get; set; }

        [Required]
        [Display(Name = "Business Type")]
        public int BustypeId { get; set; }

        [Required]
        [Display(Name = "Store"), MaxLength(20)]
        public string Store_Name { get; set; }

        [Required]
        public bool Active { get; set; }

        public virtual Address Address { get; set; }
        public virtual BusinessType BusinessType { get; set; }

        public virtual ICollection StoreSerials { get; set; }
        public virtual ICollection CMUsers { get; set; }

        public virtual ICollection TransactHeaders { get; set; }

        [InverseProperty("ToStore")]
        public virtual ICollection ToStores { get; set; }
    }
    public class BusinessType
    {
        [Key]
        [Display(Name = "Id")]
        public int BustypeId { get; set; }

        [Required]
        [Display(Name = "Store")]
        public int StoreID { get; set; }

        [Required]
        [Display(Name = "Business Type"), MaxLength(15)]
        public string Business_Name { get; set; }

        [Required]
        public bool Active { get; set; }

        public virtual ICollection Stores { get; set; }
    }

    public class Address     {
        [Key]
        [Display(Name = "Id")]
        public int AddressId { get; set; }

        [Display(Name = "City")]
        public int CityId { get; set; }

        [Required]
        [Display(Name = "Address"), MaxLength(30)]
        public string Street_Name { get; set; }

        [Required, Display(Name = "Postal Code")]
        public string Postalcode { get; set; }

        public virtual City City { get; set; }

        public virtual ICollection Stores { get; set; }
        public virtual ICollection Clients { get; set; }
    }

    public class StoreSerial 
    {
        [Key]
        public int SerialId { get; set; }
        public int? StoreId { get; set; }
        public int? RecseriesId { get; set; }
        public int? OrdseriesId { get; set; }
        public int? AdjseriesId { get; set; }
        public int? PosseriesId { get; set; }

        public virtual Store Store { get; set; }
    }


    public class TransactDetail 
    {
        [Key, Column(Order = 0)]
       // [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int StoreId { get; set; }

        [Key, Column(Order = 1)]
       // [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int SeriesId { get; set; }

        [Key, Column(Order = 2)]
       // [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int TranstypeId { get; set; }

        [Key, Column(Order = 3), ForeignKey("Product")]
       // [DatabaseGenerated(DatabaseGeneratedOption.None)]
        [Display(Name = "Product"), MaxLength(20)]
        public string BarcodeId { get; set; }

        [Key, Column(Order = 4)]
      //  [DatabaseGenerated(DatabaseGeneratedOption.None)]
        [Display(Name = "UOM")]
        public int PackageId { get; set; }

        [Required]
        [Display(Name = "Line no")]
        public int Line_no { get; set; }

        [Column(TypeName = "Date")]
        [Display(Name = "Expiry Date")]
        public DateTime? Expiry_date { get; set; }

        [Display(Name = "Wholesale Qty")]
        public decimal Wholesale_qty { get; set; }

        [Display(Name = "Wholesale Cost")]
        public decimal Wholesale_cost { get; set; }

        [Display(Name = "Conversion")]
        public decimal Conversion_qty { get; set; }

        [Display(Name = "Retail Qty")]
        public decimal Retail_qty { get; set; }

        [Display(Name = "Retail Cost")]
        public decimal Retail_cost { get; set; }

        [Display(Name = "Discount")]
        public decimal Discount_amt { get; set; }

        [Display(Name = "Sale Price")]
        public decimal Sale_price { get; set; }

        [Required]
        [MaxLength(1)]
        public string Status { get; set; }

        public virtual Product Product { get; set; }

        [ForeignKey("Store,StoreSerial,TransType")]
        public virtual TransactHeader TransactHeader { get; set; }      

    }

    public class TransactHeader
    {
        [Key, Column(Order = 0)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        [Display(Name = "Store")]
        public int StoreId { get; set; }

        [Key, Column(Order = 1)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        [Display(Name = "Series")]
        public int SeriesId { get; set; }

        [Key, Column(Order = 2), ForeignKey("TransType")]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int TranstypeId { get; set; }

        [Required, ForeignKey("ToStore")]       
        //[Required]
        [Display(Name = "To")]
        public int ToStoreId { get; set; }

        [Required, ForeignKey("Client")]
        [Display(Name = "Client")]
        public int ClientId { get; set; }

        [Required, ForeignKey("Payment")]
        [Display(Name = "Payment")]
        public int PaymentId { get; set; }

        [Required]
        [Display(Name = "Invoice"), MaxLength(15)]
        public string InvoiceId { get; set; }

        [Required]
        [Column(TypeName = "Date")]
        [Display(Name = "Invoice Date")]
        public DateTime Invoice_date { get; set; }

        [Display(Name = "Total Items")]
        public int? Total_items { get; set; }

        [Display(Name = "Gross Amount")]
        public decimal? Gross_amount { get; set; }

        [Display(Name = "Freight Charge")]
        public decimal? Freight_charge { get; set; }

        [Display(Name = "Discount Amount")]
        public decimal Discount { get; set; }

        [Display(Name = "Percentage Discount")]
        public decimal Percentage_discount { get; set; }

        [Display(Name = "Net Amount")]
        public decimal Net_amount { get; set; }

        [Display(Name = "Note"), MaxLength(50)]
        public string Note { get; set; }

        [Required]
        [MaxLength(1)]
        // 1,Cancelled, 2,Pending, 3,Done     
        public string Status { get; set; }

        public virtual Store Store { get; set; }
        public virtual Store ToStore { get; set; }

        public virtual Client Client { get; set; }
        public virtual Payment Payment { get; set; }
        public virtual TransType TransType { get; set; }

        public virtual ICollection TransactDetails { get; set; }
    }
     
<pre>
 protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.HasDefaultSchema("cmdata");
        builder.Conventions.Remove<OneToManyCascadeDeleteConvention>);          


        builder.Entity<RoleMenu>().ToTable("RoleMenus", "admin");
        builder.Entity<Menu>().ToTable("Menus", "admin");

        builder.Entity<RoleMenu>().HasKey(r => new { r.RoleId, r.MenuId, r.ParentmenuId });
        builder.Entity<ProductPrice>().HasKey(p => new { p.BarcodeId, p.StoreId, p.PackageId });
        builder.Entity<ProductStock>().HasKey(p => new { p.BarcodeId, p.StoreId, p.Expiry_date, p.PackageId });
        builder.Entity<TransactHeader>().HasKey(th => new { th.StoreId, th.SeriesId, th.TranstypeId });                     
        builder.Entity<TransactDetail>().HasKey(td => new { td.StoreId, td.SeriesId, td.TranstypeId, td.BarcodeId, td.PackageId });
  }

Error when add-migration in nugget packag console: Unable to determine the relationship represented by navigation property 'TransactHeader.TransactDetails' of type 'ICollection'. Either manually configure the relationship, or ignore this property from the model.

characters from inside a view are misencoded by the razor renderer. for instance:

MyPartial.cshtml: á á á

MyView.cshtml: á á á @Html.Partial("_MyPartial")

The final output is rendered as á á á � � �

Is this an expected behaviour?

First of all, Let me explain what's going on. The user enters the start and end dates then the form is submitted. the duration between the start and end dates are calculated and then it is redirect to another view where based on the calculated days a for loop create multiple forms on a single view as shown below in code.

Can you help me with the following:

when it is redirected to the second page, each Date (input field) in the form displays dates (from start to end date) and is incremented and also it is disable so that the user cannot make any changes. example: the starting date is 22/04/2017 and the ending date is 25/04/2017

the second form display

Date: 22/04/2017 Description: something

Date: 23/04/2017 Description: something

Date: 24/04/2017 Description: something

Date: 25/04/2017 Description: something

This is my ViewModel

public class DateViewModel
{

[Display(Name = "Start Date: ")]
    [DataType(DataType.Date)]
    [Required(ErrorMessage = "The Start Date is required.")]
    public DateTime Start_Date { get; set; }

    [Display(Name = "End Date: ")]
    [DataType(DataType.Date)]
    [Required(ErrorMessage = "The End Date is required.")]
    public DateTime End_Date { get; set; } 
}

This is My View

<h2>Comapre Dates</h2>

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Start_Date, htmlAttributes: new { 
@class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Start_Date, new { htmlAttributes 
= new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Start_Date, "", new { 
@class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.End_Date, htmlAttributes: new { @class 
= "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.End_Date, new { htmlAttributes = 
new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.End_Date, "", new { 
@class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

Now this is my Controller

public ActionResult Dates()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Dates(DateViewModel dates)
    {
        if (ModelState.IsValid)
        {
            if(dates.End_Date< dates.Start_Date )
            {
                ModelState.AddModelError("", "The Ending date is greater 
than the Starting date");
            }else
            {
                //Number of Days = Duration of the holiday
                double numberOfDays = (dates.End_Date - 
 dates.Start_Date).TotalDays;

                ViewData["NumberOfDays"] = numberOfDays;
                //The starting date in DateTime Data type
                var StartingDate = new DateTime(dates.Start_Date.Year, 
dates.Start_Date.Month, dates.Start_Date.Day);
                //This array will store date(s) depending on the number of 
days calculated
                DateTime[] data = new DateTime[(int)numberOfDays];
                //temporary storing incremented date so it can be added to 
the array
                DateTime tempDate = new DateTime();
                //for loop to store the incremented date(s) in each 
                for (int counter = 0; counter < numberOfDays; counter++)
                {
                    tempDate = StartingDate.AddDays(counter);
                    data[counter] = tempDate;
                    StartingDate.AddDays(counter);
                }

                ViewData["data"] = data;

                return new RedirectResult(@"~\Date\holiday");
            }
        }


        return View();
    }



 public class HolidayViewModel
{
    [Display(Name = "Date: ")]
    public DateTime Date { get; set; }

    [Display(Name = "Description: ")]
    [Required(ErrorMessage = "The description is required.")]
    public string Description { get; set; }

}


<h2>CreateSubEvent</h2>

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
  @for (int counter = 0; counter <= 
Convert.ToInt32(ViewData["NumberOfDays"]); counter++)
    {
        <h4 class="text-left">Day @(counter)</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
                    </div>
                </div>
    }
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Create" class="btn btn-default" />
                    </div>
                </div>  
            </div>
    }

I'm trying to apply localization on _Layout.cshtml

_Layout.cshtml

@using Microsoft.AspNetCore.Http.Extensions
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization

@inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
@inject IViewLocalizer LayoutLocalizer


<!DOCTYPE html>
<html>
<head>

</head>
    <body>
        <div style="margin:38px;margin-top:56px;" class="hidden-sm-down">
            <h2>@LayoutLocalizer["WelcomeHeader"] <b class="text_border_darkblue">MyTitle</b></h2>
            <div style="text-align:center;margin-top:42px;">
                @LayoutLocalizer["WelcomeSub"]
            </div>
        </div>
    </body>
</html>

The resource files are named named: Views.Shared._Layout.no.resx (I've tried renaming to .Layout.no.resx without any luck)

The localization works on all views except _Layout

first of all, I couldn't find a way to phrase my problem in one sentence, so I'll try to be more explicit in the post. So I've been developing on VS, essentially doing web development with Razor MVC, for almost a year now and there's something that has been bugging me. On most of my projects I use a unique stylesheet in which I put all of my rules. My problem is, if I reload the page, the CSS won't apply and I have to make a change to my CSS and save it for the rest of the sheet to works. I also noticed that if I leave VS, the CSS now apply permanently. So it's not really a big issue that won't let me work properly, but still it's a bit boring to have to change a value and then hit ctrl+z each time I reload the page.

So I wanted to know if anyone had had the same problem, and if yes what was the solution; and if no, I'll listen to any idea.

Thanks for your time and have a nice day :)

I have this error when I try to debug this code in Visual Studio using ASP.NET. I have a room table and booking table that are both populated with data. The idea is for the statement to take user defined dates from a form (vb variable arriveDate and departDate) and size of room (vb variable bedno) and return all available rooms that match the user selected room size as well as return rooms that are not booked between the dates the user chose. I have given the variables values already temporarily for testing purposes. I then use the results to populate a grid on a form page. The code is as follows:

    Dim bedno As Integer = 3
    Dim arriveDate As Date = Date.FromOADate(12 / 8 / 2017)
    Dim departDate As Date = Date.FromOADate(17 / 8 / 2017)

    Using con As New SqlConnection(constr)


        Using cmd As New SqlCommand("SELECT RoomTable.RoomNumber, RoomTable.RoomBeds, RoomTable.RoomPricePerNight, BookingTable.RoomNumber, BookingTable.ArriveDate, BookingTable.DepartDate FROM RoomTable LEFT JOIN BookingTable ON ROoomTable.RoomNumber=BookingTable.RoomNumber WHERE(BookingRoomTable.RoomBeds = " & bedno & ") AND (" & arriveDate & "NOT BETWEEN BookingTable.ArriveDate AND BookingTable.DepartDate) AND (" & departDate & "NOT BETWEEN BookingTable.ArriveDate AND BookingTable.DepartDate)")
            Using sda As New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dt As New DataTable()
                    sda.Fill(dt)
                    GridView1.DataSource = dt
                    GridView1.DataBind()
                End Using
            End Using
        End Using
    End Using
End Sub

All that comes up is an error saying "incorrect syntax near ':'" and I can't figure out the problem. Any help is much appreciated, thanks.

When clicked a button, I am trying to get the selected row value from a gridview and do something with that value but i am getting this error:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

and the code is failing at this line:

int rowIndex = Convert.ToInt32(e.CommandArgument);

here is my code:

 <asp:GridView ID="gvDetail" runat="server" CssClass="table table-hover table-bordered table-responsive" ForeColor="#333333" GridLines="None"
                CellPadding="4" PageSize="200" OnRowCommand="GridViews_RowCommand"
                AutoGenerateColumns="false" AllowSorting="true" AllowPaging="true" EnableViewState="False">
                <AlternatingRowStyle BackColor="#F3F3F3" />
                <Columns>

                  <asp:BoundField DataField="Category" HeaderText="Category" />
                  <asp:BoundField DataField="name" HeaderText="Name" />               
                  <asp:BoundField DataField="volume_paid" DataFormatString="{0:C0}" HeaderText="Spend" />

                  <asp:ButtonField HeaderText="Spend Metrics" ButtonType="Image" ImageUrl="~/img/mail.png" ControlStyle-Width="30px" ControlStyle-Height="30px" CommandName="Select"  />
                  <asp:ButtonField HeaderText="Request Call/Meeting" ButtonType="Image" ImageUrl="~/img/mail.png" ControlStyle-Width="30px" ControlStyle-Height="30px" CommandName="Select1"  />

                </Columns>
                <HeaderStyle CssClass="GridviewScrollHeader" BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                <RowStyle CssClass="GridviewScrollItem" ForeColor="#000066" />
              </asp:GridView>

code behind:

 protected void GridViews_RowCommand(object sender, GridViewCommandEventArgs e)
    {
       SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConn"].ToString());

      SqlDataAdapter da = new SqlDataAdapter(@"select min(month_key) as minKey, max(month_key) as maxKey from myTable", con);
      DataTable dtSETS = new DataTable();

      da.Fill(dtSETS);

      if (dtSETS.Rows.Count > 0)
      {
        DataRow dtSETS_row = dtSETS.Rows[0];

        int minKey = dtSETS_row.Field<int>("minKey");
        int maxKey = dtSETS_row.Field<int>("maxKey");


        if (e.CommandName == "Select")
        {
          ///Determine the RowIndex of the Row whose Button was clicked.
          int rowIndex = Convert.ToInt32(e.CommandArgument);
          string category = gvDetail.Rows[rowIndex].Cells[0].Text;
          string name = gvDetail.Rows[rowIndex].Cells[1].Text;         
          string volumepaid = gvDetail.Rows[rowIndex].Cells[2].Text;

         // do something...

        }

        if (e.CommandName == "Select1")
        {
          // do something...

        }


      }
    }

I am attempting to create a custom User Control that is usable in the Acumatica Framework... Documentation is very limited so I was hoping someone may have some experience/examples of how best to implement?

It appears possible by creating a WebControl derived from PXWebControl & creating a global JS function with a matching name.

I'm trying to avoid duplicating the URL patterns in my application. Currently I have them as annotations at the controller or its methods and I have a service that "knows" the patterns and can generate URLs for resources.

I know the play framework and its "reverse routes". Is there something like that in ASP.NET Core?

In my project i get a JSON string as out put in which i get a result

"hello world\nsecond line\nthird line\n"

But i want this to appear in a text box in .net, in new line..Insted i'am getting the above given string in textbox.

I have a problem like in the title. When the message is added, the message throws an error. When I comment message.PersonSender = person; it works. Will anyone help to solve the problem? Thank you in advance.

[HttpPost]
    public async Task<ActionResult> AppForPayPost(AppForPayViewModel.PeriodListEnum PeriodList, AppForPayViewModel.RateEnum Rate)
    {
        // try

        var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
        Person person = user.person;
        Message message = new Message();

            message.Name = "Zaświadczenie o wynagrodzeniu";
            message.PersonSender = person;
            //dodanie pola np. message.podanie boolean, jesli true to admin bedzie otwieral
            // personreceiver = null
            // message.PersonReceiver = user.person;//unitofwork.PersonGetRepo.GetPersonByRole("Administrator");
            message.Added = DateTime.Now;
            //message.Content = "Zwracam się z uprzejmą prośbą wydanie zaświadczenia o wynagrodzeniu " + Rate + " za ostatni " + PeriodList + "."
            //  + "<br />Z poważaniem" + user.person.Name + " " + user.person.Surname;
            message.NumberVisits = 0;
            unitofwork.RefreshAll();
            unitofwork.Repository<Message>().Add(message);


 public void RefreshAll()
    {
        foreach (var entity in db.ChangeTracker.Entries())
        {
            Detach(entity);
        }
    }
    public void Detach(object item)
    {
         ((IObjectContextAdapter)db).ObjectContext.Detach(item);

    }

How to export datatable data to ms word in window application . in the datatable i have some field with some image name image come from server

i am trying this

string st = startdate.Text;
            string ed = enddate.Text;
            string strquery = "select a.[tital],a.[description],a.[facebook],a.[twitter],a.[linkedin],a.[website],a.[offerdetails], " +
                ",logo=(select ( case when ThumbnailImage='' then '0' else ThumbnailImage end)as ThumbnailImage from [dbo].[ImageLinks] b where b.Id=a.[image]),bannerimage=(select ( case when ThumbnailImage='' then '0' else ThumbnailImage end)as ThumbnailImage from [dbo].[ImageLinks] b where b.Id=a.bannerimageID)," +
                "productimage=(select ( case when ThumbnailImage='' then '0' else ThumbnailImage end)as ThumbnailImage from [dbo].[ImageLinks] b where b.Id=a.productimageID),serviceimage=(select ( case when ThumbnailImage='' then '0' else ThumbnailImage end)as ThumbnailImage from [dbo].[ImageLinks] b where b.Id=a.serviceimageID)from [dbo].[ADs]" +
                " a where   (CASE WHEN LEFT(CreatedAt, 1) LIKE '[0-9]' THEN CONVERT(VARCHAR(10), CONVERT(datetime, CreatedAt,   1), 101) ELSE CONVERT(VARCHAR(10), CONVERT(datetime, CreatedAt, 109), 101) END)" +
               "between (convert(varchar(15),'" + st + "',106)) and (convert(varchar(15),'" + ed + "',106)) order by a.[type] desc";
            SqlDataAdapter da = new SqlDataAdapter(strquery, Properties.Settings.Default.MompreneursIndiaContext);
            DataSet ds = new DataSet();
            da.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0];

            string csv = string.Empty;

            //Add the Header row for CSV file.
            foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
                csv += column.HeaderText + ',';
            }

            //Add new line.
            csv += "\r\n";

            //Adding the Rows
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    //Add the Data rows.
                    if (cell.Value != null)
                    {
                        csv += cell.Value.ToString().Replace(",", ";") + ',';
                    }
                }

                //Add new line.
                csv += "\r\n";
            }

            //Exporting to CSV.
            string folderPath = "C:\\CSV\\";
            File.WriteAllText(folderPath + "DataGridViewExport.csv", csv);

In this code export my datatable date to word but not in a suitable format. but only the text field. i am new in window application. CAn anyone help me please

My objective now is to become a good backend programmer and I want to learn ASP.Net. I already have a good experience with databases like Sql Server and PLSQL and I feel I ll be good at serverside programming. Right now issue I have is to decide where to start. I found some tutorials for asp.net mvc 5 and asp.net core mvc, also I heard that there are some changes for asp in .net 5. I need an advice which one I should use, I know that asp core mvc is a newer version.

First consider the following code snippet generated by asp.net core mvc scaffolding.

        // GET: Students/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var student = await _context.Students
                .SingleOrDefaultAsync(m => m.ID == id);
            if (student == null)
            {
                return NotFound();
            }

            return View(student);
        }

        // POST: Students/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var student = await _context.Students.SingleOrDefaultAsync(m => m.ID == id);
            _context.Students.Remove(student);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }

There are some differences in HttpGet and HttpPost action methods as follows:

  • id is nullable in Get but not nullable in Post.
  • The preliminary check as follows is only in Get.

    if (id == null)
    {
        return NotFound();
    }
    
    var student = await _context.Students
                .SingleOrDefaultAsync(m => m.ID == id);
    if (student == null)
    {
       return NotFound();
    }
    

Questions

Because the posted fields can be tempered, why is there no preliminary check in HttpPost action method?

Stack Trace: [Exception: AppPress not initialized. Call InitAppPress on Application load] AppPressFramework.AppPressHandler..ctor(Object appLogic) +350 Application.Index.Page_Load(Object sender, EventArgs e) +90 System.Web.UI.Control.OnLoad(EventArgs e) +109 System.Web.UI.Control.LoadRecursive() +68 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4498

I have my models in a .NET Standard library, which I believed would make it easier to share the project between .NET Framework and .NET Core projects. My web project is MVC5, because I need SignalR which is not yet ready for .NET Core. From my web project, I just started getting this error:

CS0012: The type 'List<>' is defined in an assembly that is not referenced.
You must add a reference to assembly 'System.Collections, Version=4.0.10.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

I currently have NETStandard.Library 1.6.1 in the web project. This requires a version of System.Collections greater than or equal to 4.3, which I have installed. Why is Razor looking for a version of System.Collections lower than what I have installed? I can access the item, which is a property of type list on one of the classes in my domain project, in the controller without any problems. How can I get razor to look for version 4.3.0?

I am working on a Shopping cart application. It has already been developed by some developer. But i tried to rebuild it but i am getting the following exception

An exception of type 'System.NullReferenceException' occurred in App_Web_jwfiir5n.dll but was not handled in user code Additional information: Object reference not set to an instance of an object.

The Code in my View is below:

 <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                      <td>@(Model.IndexOf(item) + 1)</td>
                      <td><a style="color:cornflowerblue" title="Click to see the product detail" href="/admin/ProductDetail?productId=@item.ProductId"> @item.Tbl_Product.ProductName</a></td>
                      <td>@(item.Tbl_Members.FirstName + " " + item.Tbl_Members.LastName)</td>
                      <td>@item.Tbl_Members.EmailId</td>
                    </tr>
                }
             </tbody>

And The Controler side is below:

 public ActionResult OrderDetail(int productId) 
{
    List<Tbl_Cart> ProductOrders = _unitOfWork.GetRepositoryInstance<Tbl_Cart>().GetListByParameter(i => i.CartStatusId == 3 && i.ProductId == productId).ToList(); 
    return View(ProductOrders); 
} 

Can anyone help me with this error.

I have a WebAPI app with Individual Accounts. All of the controllers have the [Authorize] attribute.

I want the users to only be able to access the WebAPI through my desktop C# app. I don't want anyone accessing my WebAPI endpoints by sending requests from something like PostMan.

Only my application should be able to access the endpoints.

Any idea how to do this?