This is my combined model:
public class AddArticleModel
{
public TBL_ARTICLES Article { get; set; }
public IEnumerable<TBL_CATEGORIES> Categories { get; set; }
}
And controller that is use model.
public ActionResult AddArticle()
{
AddArticleModel AddArticleModel = new AddArticleModel();
AddArticleModel.Categories = entity.TBL_CATEGORIES.Select(a => a);
return View(AddArticleModel);
}
And View :
@model DunyaYazilim.Models.AddArticleModel
@{
ViewBag.Title = "AddArticle";
}
@using (Html.BeginForm((string)ViewBag.FormAction, "Home"))
{
<fieldset>
<legend>Add Article Form</legend>
<ol>
<li>
@Html.DropDownListFor(m => m.Categories, Model.Categories.Select(c => new SelectListItem { Text = c.Name, Value = c.CategoryID.ToString() }), "-----Select Category----")
</li>
</ol>
<input type="submit" value="Send" />
</fieldset>
}
And Posted Method in controller:
[HttpPost]
public ActionResult AddArticle(AddArticleModel AddArticleModel)
{
//Insert operations:
return View(AddArticleModel);
}
My question: When I posted the form, Occur an error : Object reference not set to an instance of an object. In line:13
Line 12: <li>
Line 13: @Html.DropDownListFor(m => m.Categories, Model.Categories.Select(c => new SelectListItem { Text = c.Name, Value = c.CategoryID.ToString() }), "-----Select Category----")
Line 14: </li>
Line 15: <li>
What the reason for this?
Note: There are a lot of examle in this site. I tried many of them, but I could not find reason of error.
Thanks.
I’m not sure if you posted the full code for your POST operation, but if you did then it’s wrong.
When you post data to the server, you are not posting the values of your SelectList. You are only posting the selected value. If you are just displaying the view back to the user, then the SelectList will be null. You need to repopulate it in the Post:
If you only want to return the selected category (seems odd) this will do it:
This assumes that the property on your view model is CategoryId and the property on your TBL_CATEGORIES entity is also CategoryId.