【发布时间】:2017-10-13 18:05:05
【问题描述】:
我有一个搜索表单,它将进行一些客户端验证、调用服务器操作、进行一些服务器端验证,然后返回原始视图(带有模型状态错误)或搜索结果。
为了使这种方法起作用,我需要将视图呈现为字符串,并返回 Json 结果。 我可以用这个问题中的一个答案来做到这一点:Render a view as a string
但是,如果我必须实现自己的“RenderView”类型函数,这真的是最好的方法吗?或者是否有更好的设计决策来实现这种功能? 任何帮助将不胜感激。
下面列出了代码的抽象供参考;
控制器:
public ActionResult Index()
{
return View(new SearchModel());
}
public ActionResult Search(SearchModel criteria)
{
if (!ModelState.IsValid)
return Json(new { HasErrors = true, Result = RenderViewToString("Index", criteria) });
var results = {Do Search...};
return PartialView("SearchResults", results);
}
查看:
@using(Html.BeginForm(...))
{
{form fields...}
{submit button...}
}
<div id="search-results"></div>
<script type="text/javascript">
$(document).on("submit", "form", function(e) {
if (!$(this).valid()) return false;
e.preventDefault(); // Submit the form with ajax instead.
$.ajax({
url: this.action,
type: this.method
data: $(this).serialize(),
success: function(data) {
if (data.HasErrors) {
$(document).html(data.Result);
}
else {
$("#search-results").html(data);
}
}
});
});
</script>
【问题讨论】:
标签: jquery ajax asp.net-mvc asp.net-mvc-5