DarthVader
DarthVader

Reputation: 55022

MVC with Razor creating drop down list

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);

Upvotes: 0

Views: 5270

Answers (3)

NiK
NiK

Reputation: 1857

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);

Upvotes: 2

oruchreis
oruchreis

Reputation: 866

Where do you create the model object? You use Model.Categories in the view, but you don't pass the model object to the view. You should pass the model object as the first parameter of the View method:

    ...
    catch
    {
        return View(/* here, there must be a model object */);
    }

Something like that:

    ...
    catch
    {
        var model = new NewsViewModel();
        return View(model);
        ... or ...
        return View(session.Load<NewsViewModel>(....));
    }

Upvotes: 0

Travis J
Travis J

Reputation: 82267

Try this

public int? SelectedId { get; set; }

@Html.DropDownListFor(m => m.SelectedId, Model.Categories, "--Select One--")

[HttpPost]
public ActionResult Create(NewsViewModel newsViewModel)
{
    if(ModelState.isValid())
    {
    try
    {
        using (var session = NHibernateHelper.OpenSession())
        {
            using (var tx = session.BeginTransaction())
            {
                newsViewModel.News.Category.Id = newsViewModel.SelectedId.Value;
                session.Save(newsViewModel.News); 
                tx.Commit();
            }
        }

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
    }
}

Upvotes: 0

Related Questions