开发者

ASP .NET MVC - Creating a partial view only works for 'Edit' actionresult and not 'Create'

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.


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.


When you render your create partial view, try :

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜