ASP.NET MVC 3 Viewmodel Pattern

前端 未结 1 1127
别跟我提以往
别跟我提以往 2020-12-06 03:23

I am trying to work out the best way of using a viewmodel in the case of creating a new object.

I have a very simple view model that contains a contact object and a

相关标签:
1条回答
  • 2020-12-06 03:56

    Your view model seems wrong. View models should not reference any services. View models should not reference any domain models. View models should have parameterless constructors so that they could be used as POST action parameters.

    So here's a more realistic view model for your scenario:

    public class ContactCompanyViewModel
    {
        public string SelectedCompanyId { get; set; }
        public IEnumerable<SelectListItem> CompanyList { get; set; }
    
        ... other properties that the view requires
    }
    

    and then you could have a GET action that will prepare and populate this view model:

    public ActionResult Create()
    {
        var model = new ContactCompanyViewModel();
        model.CompanyList = _Service.GetAll().ToList().Select(x => new SelectListItem
        {
            Value = x.id.ToString(),
            Text = x.name
        });
        return View(model);
    }
    

    and a POST action:

    [HttpPost]
    public ActionResult Create(ContactCompanyViewModel model)
    {
        try
        {
            // TODO: to avoid this manual mapping you could use a mapper tool
            // such as AutoMapper
            var contact = new Contact
            {
                ... map the contact domain model properties from the view model
            };
            _Service.Save(contact);
            return RedirectToAction("Index");
        }
        catch 
        {
            model.CompanyList = _Service.GetAll().ToList().Select(x => new SelectListItem
            {
                Value = x.id.ToString(),
                Text = x.name
            });
            return View(model);
        }
    }
    

    and now in your view you work with your view model:

    @model ContactCompanyViewModel
    @using (Html.BeginForm())
    {
        @Html.DropDownListFor(x => x.SelectedCompanyId, Model.CompanyList)
    
        ... other input fields for other properties
    
        <button type="submit">Create</button>
    }
    
    0 讨论(0)
提交回复
热议问题