Long story short, I'm trying to add a few extra items to ViewData to make my life easier, and its an edge case that doesn't really justify its own model just for this one case. Keep reading for more specific details.
So I have a strongly typed edit view for one of my objects, everything works great until I try to put a dropdownlist on the view with an ID that does not match a property of my class.
I have this
public class MyModel
{
public String Name {get;set;}
public int ID {get;set;}
public MyOtherModel Other {get;set;}
}
public class MyOtherModel
{
public String Name {get;set;}
public int ID {get;set;}
}
I am able to update the Name
property.
I'd also like to set the Other.ID
property from a DropDownList, but its not letting me do that.
My Controller looks like this
public ActionResult EditView()
{
var da = new DataAccessClass();
var Names = da.ReadActive(); // returns MyOtherModel
var sli = new SelectList(evNames, "ID", "Name");
ViewData["OtherModelNames"] = sli;
return View();
}
My View looks like this:
<p>
<label for="EndTime">Name:</label>
<%= Html.TextBox("Name") %>
<%= Html.ValidationMessage("Name", "*")%>
</p>
<p>
<label for="EndTime">Other Name:</label>
<%= Html.DropDownList("OtherNameIDList", (SelectList)ViewData["OtherModelNames"]) %>
<%= Html.ValidationMessage("OtherNameIDList", "*")%>
</p>
I get an error on this line <%= Html.DropDownList("OtherNameIDList", (SelectList)ViewData["Names"]) %>
"There is no ViewData item with the key 'OtherNameIDList' of type 'IEnumerable'."
My expectation is that in the controller action that accepts the POST, I will manually use the FormCollection[] to read out that ID and populate MyOtherModel with the correct ID.