This is my current model. The class is named exactly as my database table and I intend to use Entity Framework to get the information.
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
public string LastNameFather { get; set; }
public string LastNameMother { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public int Telephone { get; set; }
public int MobilePhone { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime DateOfRegistry { get; set; }
public DateTime LastDateLogin { get; set; }
public bool IsActive { get; set; }
public int LanceCreditBalance { get; set; }
public in开发者_如何学编程t LancesSpent { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public string Nickname { get; set; }
public string EmailVerificationCode { get; set; }
public int GenderId { get; set; }
public virtual Gender Gender { get; set; }
public int CityId { get; set; }
public virtual City City { get; set; }
}
How would my controllers look like?
[HttpGet]
public ActionResult Register()
{
//How do I load the Cities and Genders here as dropdownlists? Remember
//they are foreign key values.
return View();
}
[HttpPost]
public ActionResult Register()
{
if (ModelState.IsValid)
{
//Actually save the user here.
RedirectToAction("Index", "Home");
}
//Something went wrong, redisplay the form for correction.
return View(model);
}
It's not really a wise choice to use the Database model in the View. You should use a ViewModel. In the ViewModel you should have the properties you need to fill in the view.
So in your case you would probably need all the properties from the User Model and 2 SelectLists for your Cities and Genders.
So you should have this:
View Model
public class InsertUserViewModel
{
///All the properties for your User
///The 2 SelectLists
///2 properties for the selectedValues from thoses list.
public List<SelectListItem> Cities{ get; set; }
public int/string or whatever SelectedCity { get; set; }
}
Get
[HttpGet]
public ActionResult Register()
{
InsertUserViewModel oNewUserViewModel = new InsertUserViewModel();
//Fill in the SelectLists values with the values from your database
List<SelectListItem> Cities= new List<SelectListItem>();
Cities.Add(new SelectListItem() { Text = "New York", Value = "0", Selected = true});
Cities.Add(new SelectListItem() { Text = "Paris", Value = "1", Selected = false});
return View();
}
Post
[HttpPost]
public ActionResult Register(InsertUserViewModel oPostedUserViewModel)
{
if (ModelState.IsValid)
{
//Make a new User object with the properties from the ViewModel ant save it.
RedirectToAction("Index", "Home");
}
//Something went wrong, redisplay the form for correction.
return View(model);
}
Your View
@Html.DropDownListFor(model => model.SelectedCity , Model.Cities)
精彩评论