问题
I am new to ASP.NET MVC and please help me rather than criticizing the question.
I have a registration form which has 4 classes named form, country, state, city. The last three are for populating the cascading Dropdownlist in my form
public partial class form
{
public int Id { get; set; }
public string UniqueId { get; set; }
public string Country{ get; set; }
public string state { get; set; }
public string city { get; set; }
public Nullable<long> PinCode { get; set; }
public Nullable<long> MobileNumber { get; set; }
public string EmailId { get; set; }
and some fields ......
public virtual Country countries { get; set; }
public virtual State states { get; set; }
public virtual City cities { get; set; }
}
The last three virtual properties I have added to the class
The country class has:
public int CountryId { get; set; }
public string CountryName { get; set; }
public virtual ICollection<tbTehsil> states { get; set; }
The state and city class have similar fields.
Now I want to get all values from my district class and populate my ddl.
This code is in Home controller having index action method
FarmerDbContext db = new FarmerDbContext();
List<Country> country= db.Country.ToList();
return View(country);
In my Index.cshtml I have strongly typed it with form class
@model IEnumerable<test.Models.form>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.DropDownListFor(x => x.countries, new SelectList(Model.countries, "CountryId", "CountyName"),"----select Country -----")
but it gives an error on my dropdownlist and when I remove IEnumerable<> from top of this view it gives another error which is quite obvious.
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[test.Models.country]', but this dictionary requires a model item of type 'test.Models.form'.
回答1:
I don't think you really need a collection of form objects for your Index.cshtml. You should create just one form object and then initialize it with all the information you need and then pass it to your model.
public class HomeController : Controller
{
public ActionResult Index()
{
var form = new test.Models.form();
FarmerDbContext db = new FarmerDbContext();
form.Countries = db.Country.ToList();
return View(form);
}
}
Index.cshtml:
@model test.Models.form
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.DropDownListFor(x => x.countries, new SelectList(Model.countries, "CountryId", "CountryName"), "----- Select Country -----")
来源:https://stackoverflow.com/questions/31490447/what-should-i-pass-from-the-controller-to-my-view-in-asp-net-mvc-4-with-entity-f