Reputation: 6836
I've got a form that has a dropDownlist using the Model to fill the list, the view is rendered. The issue is that when i press the submit button, a null pointer exception for Model is thrown. I want to receive the value selected in the Post Action.
Here is my code:
Model:
public class BillViewModel
{
public List<SelectListItem> ClientList { get; set; }
public int SelectedClient { get; set; }
}
Controller Action:
public ActionResult Index()
{
var billRepo = new BillRepo();
var bill = new BillViewModel {ListProducts = billRepo.GetAllProducts()};
bill.ClientList = new List<SelectListItem>();
List<Client> allClientList = billRepo.GetAllClients();
foreach (Client client in allClientList)
{
var item = new SelectListItem() { Value = client.ClientId.ToString(), Text = client.Name };
bill.ClientList.Add(item);
}
ViewBag.ClientSelect = new SelectList(billRepo.GetAllClients(), "value", "text", bill.SelectedClient);
bill.SelectedClient = 1;
return View(bill);
}
[HttpPost]
public ActionResult Index(BillViewModel billViewModel)
{
return View();
}
View: this is where I get the null pointer exception in Model.ClientList
@using (Html.BeginForm())
{
@Html.DropDownListFor(item => item.SelectedClient, Model.ClientList, "Select Client")
<input type="submit" value="Aceptar"/>
}
Upvotes: 1
Views: 1248
Reputation: 879
In the [HttpPost]
action method, you are invoking the View() method without any viewmodel. Therefore the Model property inside the view is null. The solution is simply to invoke View and passing in the BillViewModel
.
Ex:
[HttpPost]
public ActionResult Index(BillViewModel billViewModel)
{
return View(billViewModel);
}
Upvotes: 2
Reputation: 887867
As the error is trying to tell you, Model.ClientList
is null.
You need to initialize the model, just like you did in the GET action. (for example, by calling the same function)
Upvotes: 2