Implementing ASP.NET MVC 3 Interface Model Binding (with ViewModel)

两盒软妹~` 提交于 2019-12-04 18:43:37

I ended up resolving the issue by first making a couple of modifications..in my question, my controller failed to use the ViewModel class I had created. Once I modified the controller to look like so:

 /// <summary>
    /// POST: /Company/Edit/5
    /// </summary>
    [HttpPost]
    public ActionResult Edit(CompanyViewModel viewModel)
    {
        var company = _companyService.GetCompany(viewModel.Company.CompanyID);

        if (company == null)
            return RedirectToAction("Index");

        if (ModelState.IsValid)
        {
            if (TryUpdateModel<ICompanyUpdateAsUser>(company, "Company"))
            {
                _companyService.SaveCompany();
                return RedirectToAction("Details", new { companyId = viewModel.Company.CompanyID });
            }
        }

        return View(viewModel);
    }

I found that everything appeared to be working properly, but as stated in the comments above TryUpdateModel simply DID NOT work, though returning true!

After sifting through tons of Stack Overflow & other forum posts, I eventually found that TryUpdateModel does not work on fields, only properties. To get it working properly I had to modify my ViewModel to look like so:

public class CompanyViewModel
{
    public Company Company { get; set; }

    public CompanyViewModel(Company company)
    {
        Company = company;
    }

    public CompanyViewModel()
    {
        Company = new Company();
    }
 }

Such a silly mistake, though I feel this point is far overlooked by many of the model binding tutorials I have read.

Hopefully this answer will save someone some time.

There should be an overload of TryUpdateModel that takes in a prefix. Since it sounds like your original view model contained your Company object, then the name of the form fields that were generated for the Company object (assuming you're using standard form input names), contain a prefix of "Company", it looks like you've recognized this with the model that the method is taking in, try using the same prefix when updating your domain object.

FYI, it's generally not best practice to use your domain objects in your view model, the main reason for this is that there could be fields you don't want to allow a user to update. If a user has enough knowledge about your domain, they can add additional form fields into the post data, and MVC would blindly update those property/fields and that could cause a problem. There are ways of telling MVC to exclude certain properties/fields when binding, but it becomes a maintenance nightmare and is usually easier to use separate objects for your views.

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