I have the follwing code, I m able to create a drop down list but when I submit, I get an Object reference not set to an instance of an object exception. News class has Category and Category class have Id, Name, Order.
How can I fix this?
My view:
<div class="editor-field">
@Html.DropDownListFor(m => m.News.Category.Id, Model.Categories, "Select One")
@Html.ValidationMessageFor(m => m.News.Category)
</div>
The view model:
public class NewsViewModel
{
public string SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
public News News { set; get; }
}
And the controller action:
[HttpPost]
public ActionResult Create(NewsViewModel newsViewModel)
{
try
{
using (var session = NHibernateHelper.OpenSession())
{
using (var tx = session.BeginTransaction())
{
session.Save(newsViewModel.News);
tx.Commit();
}
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I m getting the exception while saving the model session.Save(newsViewModel.News);
Is your dropdown being populated with values on your get request?
if yes, on submit, is the viewModel’s m.News.Category.Id property is set with the id of the value you’ve selected in the dropdown?
if yes, then its not the problem with the dropdown…it is something to do with the NHibernate session that you are using…try something like (News)session.Save(newsViewModel.News);