How to use ViewModels in ASP.NET MVC?

后端 未结 2 1308
忘了有多久
忘了有多久 2020-12-09 21:15

I just started learning about ViewModels in ASP.NET MVC. So, I thought of implementing a sample example as below:

Business Entity

pu         


        
2条回答
  •  情歌与酒
    2020-12-09 21:57

    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

                
                    @Html.TextBoxFor(m=> m.a)
                
    
                
                    @Html.TextBoxFor(m=> m.b)
                
    

    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

提交回复
热议问题