【问题标题】:HTTP Post request from different controller actions and ModelState来自不同控制器操作和 ModelState 的 HTTP Post 请求
【发布时间】:2012-03-04 16:26:48
【问题描述】:

我对 ASP.NET MVC 3 应用程序有一个奇怪的需求,它阻碍了我当前的进度。情况如下:

我有一个小的产品搜索引擎,我在多个页面上呈现这个搜索引擎。此 SE 向 product 控制器的 search 操作发出 HTTP POST 请求。到这里还好。

假设我在home 控制器的index 操作(/home/index)。我进行搜索并检查是否ModelState.IsValid。结果,它是无效的。所以,我应该用输入的模型返回这个(这样用户就不会丢失值)和模型状态错误。但是当我这样做时,我最终得到了不同的 URL(/product/search)。

如果我进行重定向,我会丢失 ModelState 并且无法显示错误消息。

到目前为止,我有不同的解决方案,但它们看起来都很脏。有什么想法吗?

编辑

这是一个演示这个的小项目:

这是ProductController:

public class ProductController : Controller {

    [HttpPost]
    public ActionResult Search(SearchModel searchModel) {

        if (ModelState.IsValid) { 
            //Do some stuff...

            return RedirectToAction("Index", "SearchResult");
        }
        return View(searchModel);
    }
}

这是SearchModel:

public class SearchModel {

    [Required]
    public string ProductCategory { get; set; }

    [Required]
    public string ProductName { get; set; }
}

这是 *_SearchPartial*:

@model MvcApplication20.SearchModel

@using (Html.BeginForm("search", "product"))
{
    @Html.EditorForModel()

    <input type="submit" value="Search" />
}

最后是 Home 控制器 Index 渲染 *_SearchPartial* 的操作视图:

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>

@Html.Partial("_SearchPartialView")

这里,当我提交表单时,如果模型状态失败,我应该如何处理Product 控制器Search 操作?

【问题讨论】:

  • 我不太明白您的 home/index/ 中的模型状态与您的搜索有何关系,(1) 您如何呈现您的搜索页面?盒子?在您的多个页面上?
  • @gideon 我的搜索引擎处于局部视图中,它被包裹在一个指向/product/search 的html 表单中,以发出http post 请求。由于我在多个页面上呈现这个,控制器和动作总是不同的。
  • 你能展示代码你是怎么做的吗?
  • 你能给我们看看代码吗?我需要的尤其是您在模型状态中拥有的东西。只是搜索词吗?
  • @tugberk 搜索引擎部分是否也包含搜索引擎结果?

标签: asp.net-mvc asp.net-mvc-3 modelstate asp.net-mvc-validation


【解决方案1】:

这里,当我提交表单时,如果模型状态失败,应该如何 我继续执行产品控制器搜索操作吗?

通常在这种情况下,您应该渲染_SearchPartialView,但不是作为部分视图,而是作为带有布局的完整视图,以便用户可以修复他的错误。在这种情况下无需留在 Home/Index:

[HttpPost]
public ActionResult Search(SearchModel searchModel) {

    if (ModelState.IsValid) { 
        //Do some stuff...

        return RedirectToAction("Index", "SearchResult");
    }
    // since we are returning a view instead of a partial view,
    // the _SearchPartialView template should be displayed with the layout
    return View("_SearchPartialView", searchModel);
}

如果您想在出错时留在同一页面上,您可以使用 AJAX 调用来执行搜索。因此,您将 AJAXify 这个搜索表单,然后在成功回调中测试 Search 操作的结果,并根据它决定是否刷新部分以显示错误或使用 window.location.href 重定向到结果操作:

类似的东西:

$(document).on('submit', '#searchForm', function() {
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(), 
        success: function(result) {
            if (result.redirectTo) {
                // no validation errors we can redirect now:
                window.location.href = result.redirectTo;
            } else {
                // there were validation errors, refresh the partial to show them
                $('#searchContainer').html(result);

                // if you want to enable client side validation
                // with jquery unobtrusive validate for this search form
                // don't forget to call the .parse method here 
                // since we are updating the DOM dynamically and we
                // need to reattach client side validators to the new elements:
                // $.validator.unobtrusive.parse(result);
            }
        }
    });
    return false;
});

这显然假设您现在已将部分调用包装在一个带有 id="searchContainer" 的 div 中,并且您在生成搜索表单时提供了一个 id="searchForm":

<div id="searchContainer">
    @Html.Partial("_SearchPartialView")
</div>

现在是搜索操作:

[HttpPost]
public ActionResult Search(SearchModel searchModel) {

    if (ModelState.IsValid) { 
        //Do some stuff...

        return Json(new { redirectTo = Url.Action("Index", "SearchResult") });
    }
    return PartialView("_SearchPartialView", searchModel);
}

【讨论】:

  • 谢谢达林。这是我尝试过的方法之一,我在上面说这是肮脏的(不过我不确定是否如此)。事实上,这就是我的救援计划。我想做的是留在页面上,但我还没有找到这样做的好方法,而且看起来没有必要呆在那里。嗯,我想我正在改变主意。
  • 渲染部分本身看起来是最干净的方式。
  • @tugberk,如果你想留在页面上,你可以使用 AJAX。我已经用一个例子更新了我的答案。
【解决方案2】:

据我所知,在执行 RedirectToAction 时模型状态会丢失,解决方案是将模型状态保存在 TempData 中,我正在使用的一个示例是这样的:

http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#prg

这也在各种帖子中进行了讨论,例如MVC Transfer Data Between Views

【讨论】:

  • 我关闭了会话状态并创建了一个自定义 Cookie TempDataProvider 来存储字符串。所以,TempData 对我来说不是一个选择,而是一个很好的建议。
猜你喜欢
  • 1970-01-01
  • 2013-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多