开发者

ASP.Net MVC Object Reference in Edit View when using DropDownListFor()

开发者 https://www.devze.com 2022-12-28 17:32 出处:网络
This question is related to another I ask recently, it can be found here for some background information.

This question is related to another I ask recently, it can be found here for some background information.

Here is the code in the Edit ActionResult:

    public virtual ActionResult Edit(int id)
    {
        ///Set data for DropDownLists.
        ViewData["MethodList"] = tr.ListMethods();
        ViewData["GenderList"] = tr.ListGenders();
        ViewData["FocusAreaList"] = tr.ListFocusAreas();
        ViewData["SiteList"] = tr.ListSites();
        ViewData["TypeList"] = tr.ListTalkbackTypes();
        ViewData["CategoryList"] = tr.ListCategories();

        return View(tr.GetTalkback(id));
    }

I add lists to the ViewData to use in the dropdownlists, these are all IEnumerable and are all returning values.

GetTalkback() returns an Entity framework object of type Talkback which is generated from the Talkback table.

The DropDownListFor code is:

<%: Html.DropDownListFor(model=>model.method_id,new SelectList(ViewData["MethodList"] as IEnumerable<SelectListItem>,"Value","Text",Model.method_id)) %>

The record I am viewing has values in all fields. When I click submit on the View, I get an Object reference not set to an instance of an object. e开发者_StackOverflow中文版rror on the above line.

There are a number of standard fields in the form prior to this, so the error is only occurring on dropdown lists, and it is occurring on all of them.

Any ideas? This is my first foray in to MVC, C#, and Entity so I am completely lost!


If you have [HttpPost] method like that

[HttpPost]
public ActionResult Edit(Talkback model)
{
    //Do something with model
    return View(model);
}

You have to fill ViewData again. If you don't do it, you'll have Object reference not set to an instance of an object errors.

The best thing to do would be to follow POST-REDIRECT-GET patter and do it like that:

[HttpPost]
public ActionResult Edit(Talkback model)
{
    //Do something with model
    return RedirectToAction("Edit", new { id = model.id });
}

You'll have ViewData filled again by [HttpGet] method.

0

精彩评论

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

关注公众号