1

I have created a partial view for use by by the 'Edit' view of my model. I can successfully edit records but when using the partial view for my 'Create' view I get a null reference exception.

This is my partial view:

@model MvcA.Models.Reason       

        @Html.LabelFor(model => model.reason)
        @Html.EditorFor(model => model.reason)

        @Html.LabelFor(model => model.Contract)
        @Html.DropDownList("ContractId",
        new SelectList(ViewBag.Contract as System.Collections.IEnumerable,
       "ContractId","Name",Model.ContractID));

And POST ActionResult:

[HttpPost]
public ActionResult Create(Reason reason)
{
   if (ModelState.IsValid)
            {
                db.Reason.Add(reason);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            //invalid ...

The GET Create:

public ActionResult Create()
    {
        ViewBag.Contract = db.Contract.OrderBy(g => g.Name).ToList();
        var reason = new Reason();
        return View(reason);
    } 

Upon entering/selecting valid values the form submit will result in Visual Studio exiting out to the 'DropDownList' found in the partial view with a 'NullReferenceException was unhandled'.

How do I determine what is causing the null error? (I'm new to MVC)

UPDATE: The error appears to be related to the [HttpPost] Create method in my controller. I was naming the input class using the same name as one of the fields in the model...this appears to have broken the program with the null reference exception.

0

2 Answers 2

1

When you post to the create action is the model valid or invalid when you get the exception? If it is invalid, it is likely because you're returning a view to show the form with validation but are missing some of the requirements for that view (like however ViewBag.Contract is getting populated). If you show both Create actions in full it will be easier to verify this.

Sign up to request clarification or add additional context in comments.

2 Comments

I have added the 'GET' creation action.
The key is the other part of the POST creation action though -- are you populating ViewBag.Contract just like in the GET action? You need ViewBag.Contract = db.Contract.OrderBy(g => g.Name).ToList(); in the POST creation method in the part of it that redisplays the view if the model is invalid.
1

When you render your create partial view, try :

<% Html.RenderPartial("YouPartialViewName", new Reason()); %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.