I've come to the Council of Wise Wizards here at Stackoverflow because I need some magic (it seems) to fix a minor issue with my code.
I am attempting to receive data from my dropdown list, I've tried many spells... But I feel my powers are too weak. My attempts to retrieve data from the dropdown list results in my computer throwing up a little bit of sick. So I've come to you guys with hopes that your wiseness (is that even a word?) can help me to conjure up the correct code to defeat this issue.
Here's what my code looks like
The model (not very pretty for a model):
namespace HouseGaurd.Models
{
public class DropList
{
public SelectList LettingList { get; set; }
}
The controller fills up the list: (this is Httpget)
public ActionResult lettingselect()
{
var model = _db.EstateAgents;
DropList rlist = new DropList();
List<SelectListItem> listItems = new List<SelectListItem>();
foreach (var item in model)
{
listItems.Add(new SelectListItem()
{
Value = item.estateAgentID.ToString(),
Text = item.CompanyName
});
}
rlist.LettingList = new SelectList(listItems, "Value", "Text");
return View(rlist);
}
So this populates the list, this is the model that displays, so far everything works fine, the spell holds true:
<h2>Select a </h2>
@using (Html.BeginForm()) {
@Html.DropDownList("product", Model.LettingList)
<p>
<input type="submit" value="select" />
</p>
}
It populates the dropdown list with the relevant information!
Now when I hit submit and we go back to the POST controller, this is when the computer starts to throw up:
[HttpPost]
public ActionResult lettingselect(DropList viewModel)
{
using (var context = new HouseDB())
{
var agent = viewModel.LettingList.DataTextField; //null reference
var hID = context.HouseListers.Single(d=>d.user == User.Identity.Name);
var let = new Letting();
let.approved = false;
let.user = User.Identity.Name;
let.lettingAgent = agent;
let.houseID = hID.houseID;
let.noProblemsRaised = 0;
context.Lettings.Add(let);
context.SaveChanges();
}
return RedirectToAction("Complete");
}
I'm trying to get the selected value back, I tried using:
var agent = viewModel.LettingList.DataTextField; //null reference
But as stated in the code, this comes back with a null reference exception.
Wise Wizards, take a moment to share your wisdom with me on how to best approach this problem.
Many thanks. Apprentice wizard.
EDIT: this is the actual error:
Object reference not set to an instance of an object.
and this is the model in the view
@model HouseGaurd.Models.DropList
Could this be causing the problem?
"product"
, so theLettingList
property on your model can't possibly be instantiated by the model binder. If you just need to get the selected value, follow the advice in the answer you were given. If you are trying to instantiate your LettingList, you'll need to build it again. – Bennor McCarthy Mar 19 at 12:20