I have developed ASP.Net applications over the years using Webforms and I have done a few MVC applications but never actually use the framework in full, this is due to the time constraint of most of the projects. Although, I'm using the MVC structure I'm still using the old ways i.e. not using @Html.BeginForm etc. instead I user the tag etc.
I've just recently started another project, but this time I want to use the correct MVC features.
I have been reading about Best Practices in Design Patterns. In my Solution, I have Projects for the MVC application, Testing, and for Data (which is a class library that connects to the database). I'm not using Entity Framework but I'm still wondering about the proper way of creating classes for View Models.
On my Data library class I have a class call Users
public class User
{
public long Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[Required]
public long RoleId { get; set; }
}
The fields I want to render on the View are Name, Email, and a dropdownlist for the RoleId. So for a Model on the View, is it correct that it doesn't have to be the same as my Data Class? Is below a correct Model View Class?
public class UserModel
{
public Data.User User { get; set; }
public IEnumerable<KeyValuePair<long,string>> RoleList { get; set; }
}
The reason for asking is that, initially, I always assume that Model classes should be the same as your Data classes which I have read in Google that in most cases it's not. Is this correct?
Is this the correct implementation of the view?
@using (Html.BeginForm())
{
@Html.LabelFor(m=>m.User.Name)
@Html.TextAreaFor(m=>m.User.Name)
<br/>
@Html.LabelFor(m => m.User.Email)
@Html.TextAreaFor(m => m.User.Email)
<br />
@Html.LabelFor(m => m.User.RoleId)
@Html.DropDownListFor(m => m.User.RoleId, new SelectList(Model.RoleList,
"Value", "Key"),"--Please Select--")
}