0

I created scaffold delete view for delete but it doesn't work. When debugging I found that It doesnt pass the correct ID of the record to controller. Always it passes 0 as the ID and result is an exception (ystem.NullReferenceException was unhandled by user code Message=Object reference not set to an instance of an object.) .

But in the view submit button shows the correct URL with correct ID.

Controller:

    public ActionResult DeleteSubject(int id)
    {
        try
        {
            // returns the View
        }
        catch (Exception e)
        {
            // Handle and log  the exception                
        }   
    }


    [HttpPost]
    public ActionResult DeleteSubject(SubjectModel subject)
    {
        try
        {
            // Call methods for delete
        }
        catch (Exception e)
        {
            // Handle and log  the exception 
        }  
    }

View:

   @model LMS.Models.SubjectModel

   // ... form elements go here

   @using (Html.BeginForm()) { 
      <input type="submit" value="Delete" />
   }

When debugging the [HttpPost] method with a break point, object taken by the method as argument seems not initialized with values. Displaying 0s for ID fields and null for other fields.

Worked on recreating views, rewriting controller methods, changing attributes etc. But still get the issue. Appreciate your input.

(BTW created scaffold view for Create, List and Edit. They are working perfectly.)

Thanks,

Chatur

chatura
  • 4,097
  • 4
  • 19
  • 19

2 Answers2

0

When ever I post to a form I noticed having the id="form" always helps.

@using (Html.BeginForm("Create", "RunLogEntry", FormMethod.Post, new { id = "form", enctype = "multipart/form-data" }))
    {
tam tam
  • 1,870
  • 2
  • 21
  • 46
0

In MVC the default way the Id parameter is passed on the URL not on the body, that's why its null.

change the httpPost delete to;

public ActionResult DeleteSubject(int id, SubjectModel subject)

also I notice you have the // ... form elements go here outside the form I should go inside.

Pedro.The.Kid
  • 1,968
  • 1
  • 14
  • 18