4

我打算将Hotel模型传递给我的 Controller Action - 对其进行一些检查/处理,然后返回在 Partial View 中呈现的可能不同的Hotel模型。

我遇到的问题是,如果我将oHotelParameter模型传递给 Action,那么 PartialView 使用传递给 Action 的模型,而不是传递给 PartialView 方法的模型。

如果我从 Action 中删除oHotelParameter参数,则使用oHotel按预期渲染视图。

    public ActionResult _SaveMasterDetails(Hotel oHotelParameter)
    {
        //Do some processing on oHotelParameter

        //........
        Hotel oHotel = new Hotel();
        oHotel.GetHotelInfoById(14); //This gets a different Hotel object just for a test

        //For some reason oHotel is ignored and oHotelParameter is used instead unless I remove oHotelParameter 
        return PartialView("_MasterDetails", oHotel);
    }

当我调试 View 时,我看到 Model 设置为我传递给 PartialView ( oHotel ) 的值,但我看到从 Action 返回的结果包含来自oHotelParameter对象的数据。

万一它有所作为,我从 jQuery ajax 调用 Action。

谁能解释为什么会发生这种情况?

4

2 回答 2

3

我认为,如果您在回发到操作方法时更好地理解模型绑定的工作原理,那将会有所帮助。在大多数情况下,将视图模型作为参数传递给 POST 操作方法是不必要且低效的。当您将视图模型作为参数传递时(假设是强类型视图),您正在做的是两次将视图模型加载到内存中。当您进行回发时,模型将成为 BaseController 类中请求对象中表单集合的一部分(通过模型绑定),每个控制器都继承自该类。您需要做的就是从 BaseController 的 Request 对象中的 Form 集合中提取模型。碰巧有一个方便的方法 TryUpdateModel 可以帮助您执行此操作。这是你的做法

[POST]
public ActionResult Save()
{
    var saveVm = new SaveViewModel();

    // TryUpdateModel automatically populates your ViewModel!
    // TryUpdateModel also calls ModelState.IsValid and returns
    // true if your model is valid (validation attributes etc.)
    if (TryUpdateModel(saveVm)
    {
        // do some work
        int id = 1;
        var anotherSaveVm = GetSaveVmBySomeId(id);

        // do more work with saveVm and anotherSaveVm
        // clear the existing model
        ModelState.Clear();
        return View(anotherSaveVm);
    }
    // return origonal view model so that the user can correct their errors
    return View(saveVm);
}

我认为请求对象中包含的表单集合中的数据正在与视图一起返回。当您将模型作为参数传递回 post 操作方法时,我相信它是在查询字符串中传递的(请参阅 Request.QueryString)。大多数时候,最好只传递一两个原始类型参数或原始的崇敬类型,例如 int? 到一个动作方法。不需要传递整个模型,因为它已经包含在 Request 对象的 Form 集合中。如果您想检查 QueryString,请参阅 Request.QueryString。

于 2013-06-05T14:43:04.123 回答
3

当 mvc 处理表单发布时,它会用模型的详细信息填充 ModelState 对象。

这是在从 post 操作再次呈现视图时使用的,以防您因为未通过验证而将视图扔回。

如果您想传递一个新模型而不使用视图状态,那么您可以在返回视图之前调用 ModelState.Clear() ,这样您就可以将视图重新绑定到新模型。

于 2013-06-05T13:52:46.837 回答