I'm stuck creating a proper create/edit view in ASP.NET MVC5. I've got two models Dog
and Human
. A dog belongs to one Human
. I'm trying to create a dropdown in the create
and edit
views for Dog
that'll allow me to select a Human
by name for that particular Dog
. Here are my models:
Human:
public class Human
{
public int ID { get; set; }
public string Name { get; set; }
}
Dog:
public class Dog
{
public int ID { get; set; }
public string Name { get; set; }
public Human Human { get; set; }
}
My create action:
// GET: /Dog/Create
public ActionResult Create()
{
ViewBag.HumanSelection = db.Humen.Select(h => new SelectListItem
{
Value = h.ID.ToString(),
Text = h.Name
});
return View();
}
And here is the relevant part of my view:
<div class="form-group">
@Html.LabelFor(model => model.Human.Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Human, ViewBag.HumanSelection);
</div>
</div>
I get the following error when I run this:
Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper<Test.Models.Dog>' has no applicable method named 'DropDownListFor' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
I'm new to C# & the Entity framework. What am I doing wrong? Is there a way of doing this without manually querying the database? Something like the collection form helpers in Rails? I've followed a bunch of tutorials that are either old or too complicated for me to follow.
http://ilyasmamunbd.blogspot.com/2014/03/how-to-create-dynamic-dropdownlist-step.html – Md. Ilyas Hasan Mamun Nov 05 '14 at 08:45