How to use ViewModels in ASP.NET MVC?

半城伤御伤魂 提交于 2019-11-28 09:20:56

your view model should look like this

public class AddViewModel
    {
        public int a { get; set; }
        public int b { get; set; }
        public int Total { get; set; }
    }

and in the cshtml

            <td class="tdCol2Align">
                @Html.TextBoxFor(m=> m.a)
            </td>

            <td class="tdCol2Align">
                @Html.TextBoxFor(m=> m.b)
            </td>

in the controller

        [HttpPost]
        public JsonResult Add(AddViewModel model)
        {
            int iSum = model.a + model.b;
            model.Total = iSum;
            return Json(model);

        }

Edit

View model is there to render your views don't place any logic inside that. if you have more complex model then it will be hard to map Model with ViewModel. for this you can use AutoMapper or ValueInjector for mapping between model and view model.

link for automapper http://automapper.codeplex.com/

link for value injector http://valueinjecter.codeplex.com/

hope this helps

You should not use the domain (business) entities in your view model. If you do, a view model is pretty useless since it stills contains business logic which you might not want in the view. The model in your example doesn't really represent a real-world scenario, a view model is not really needed for it anyway.

A more common and trivial example of a view model is a login form: You probably have a domain model called User and you want them to log in. The User domain model can be big and just a small part of it is needed for the authentication. It also contains validation logic for the database which doesn't represent validation logic for the login form.

The User domain model:

public class User
{
    [Required]
    public string UserName { get; set; }

    [Required]
    [MaxLength(36)] // The password is hashed so it won't be bigger than 36 chars.
    public string Password { get; set; }

    public string FullName { get; set; }

    public string SalesRepresentative { get; set; }

    // etc..
}

The above domain model represents the database table thus containing validation logic to ensure integrity.

public class LoginModel
{
    [Display(Name = "User Name")]
    [Required(ErrorMessage = "Please fill in your user name.")]
    public string UserName { get; set; }

    [Required(ErrorMessage = "Please fill in your password.")]
    public string Password { get; set; }

    public bool RememberMe { get; set; }
}

The view model above contains just the properties we need for the login form and has it's own data annotations. This helps you to cleanly separate view logic and business/data logic.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!