I have a class called Entity
public class Entity
{
public string Name { get; set; }
public Location Place { get; set; }
}
and one class called Location
public class Location
{
public string Country { get; set; }
public string State { get; set; }
public string City { get; set; }
}
One Entity
contains a Location
, so I want to generate 3 dropdowns for Location
.
- Country
- State
- City
I could do it manually like
@Html.DropDownListFor(o => o.Country, new [] { new SelectListItem() { Text = "United States", Value="US" } })
<br />
@Html.DropDownListFor(o => o.State, new [] { new SelectListItem() { Text = "Some State", Value="SS" } })
<br />
@Html.DropDownListFor(o => o.City, new[] { new SelectListItem() { Text = "Some city", Value = "City" } })
But I have several places on my website that will need the exact same 3 dropdowns, like Restaurant
, Hotel
and other classes that also have a Location
. I've tried to make a partial view that starts a new form, but I get an exception:
The model item passed into the dictionary is of type 'TestMVC3Razor.Controllers.Entity', but this dictionary requires a model item of type 'TestMVC3Razor.Controllers.Location', with this code:
@model TestMVC3Razor.Controllers.Entity
@using (Html.BeginForm())
{
@Html.Partial("LocationSelector", Model.Place)
<br />
<input type="submit" value="Submit" />
}
And the partial view is
@model TestMVC3Razor.Controllers.Location
@using (Html.BeginForm())
{
@Html.DropDownListFor(o => o.Country, new [] { new SelectListItem() { Text = "United States", Value="US" } })
<br />
@Html.DropDownListFor(o => o.State, new [] { new SelectListItem() { Text = "Some State", Value="SS" } })
<br />
@Html.DropDownListFor(o => o.City, new[] { new SelectListItem() { Text = "Some city", Value = "City" } })
}
This obviously shouldn't work, but I want to do something like it, a helper like this would be perfect
@Html.LocationSelectFor(o => o.Location)
But how do I do this? I need to generate 3 dropdowns
and when I post to an action I need to get the object with bidden values.
public ActionResult(Location loc)
{
var x = String.Format("{0}, {1} - {2}", loc.City, loc.Country, loc.State);
}
How can I make this helper to create 3 dropdowns and bind values when I post?