Is there any good reason to use FormCollection instead of ViewModel?

前端 未结 11 1561
离开以前
离开以前 2020-11-27 15:09

I\'ve inherited a code base written in ASP.Net MVC 4. Every post method takes a FormCollection. Aside from annoyance of having to access the values through quot

11条回答
  •  萌比男神i
    2020-11-27 15:32

    Ok, I see the general consensus here is that it isn't liked. To offer another perspective, I've always liked using the formcollection passed into the controller on POST actions. It offers the use of the TryUpdateModel method from the controller which will map the collection to your strongly typed class. TryUpdateModel also has overloads that allow you to white list the properties of the model that you want to allow to be updated.

    if (TryUpdateModel(viewModel, new string[] { "Name" }))
    {
        //Do something
    }
    

    It still allows all the model binding you want, but helps to keep anything other than the "Name" property on my viewmodel from being updated.

    You can see more about the TryUpdateModel method here:

    http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryupdatemodel(v=vs.108).aspx

提交回复
热议问题