【发布时间】:2014-01-05 19:53:08
【问题描述】:
我正在尝试在主(索引)视图中显示部分视图:
步骤:
- 用户从索引视图中选择一个下拉项目。
- 这会显示一个包含搜索表单的部分视图。
- 用户填写搜索表单,然后单击提交按钮。
- 如果搜索表单有效,则会显示一个新页面(结果视图)。
- 否则,搜索表单部分视图应在主视图内重新显示错误
我遇到了数字 4 的问题,因为当搜索表单提交时,它仅在新窗口中显示
部分视图。我想显示整个页面:Index View + Partial View with errors.
建议?这就是我所拥有的:
图片
控制器
public class AppController : Controller
{
public ActionResult Index()
{
return View(new AppModel());
}
public ActionResult Form(string type)
{
if (type == "IOS")
return PartialView("_IOSApp", new AppModel());
else
return PartialView("_AndroidApp", new AppModel());
}
public ActionResult Search(AppModel appModel)
{
if (ModelState.IsValid)
{
return View("Result");
}
else // This is where I need help
{
if (appModel.Platform == "IOS")
return PartialView("_IOSApp", appModel);
else
return PartialView("_AndroidApp", appModel);
}
}
}
型号
public class AppModel
{
public string Platform { get; set; }
[Required]
public string IOSAppName { get; set; }
[Required]
public string AndroidAppName { get; set; }
public List<SelectListItem> Options { get; set; }
public AppModel()
{
Initialize();
}
public void Initialize()
{
Options = new List<SelectListItem>();
Options.Add(new SelectListItem { Text = "IOS", Value = "I" });
Options.Add(new SelectListItem { Text = "Android", Value = "A"});
}
}
索引.cshtml
@{ ViewBag.Title = "App Selection"; }
<h2>App Selection</h2>
@Html.Label("Select Type:")
@Html.DropDownListFor(x => x.Platform, Model.Options)
<div id="AppForm"></div> // This is where the Partial View goes
_IOSApp.cshtml
@using (Html.BeginForm("Search", "App"))
{
@Html.Label("App Name:")
@Html.TextBoxFor(x => x.IOSAppName)
<input id="btnIOS" type="submit" value="Search IOS App" />
}
AppSearch.js
$(document).ready(function () {
$("#Platform").change(function () {
value = $("#Platform :selected").text();
$.ajax({
url: "/App/Form",
data: { "type": value },
success: function (data) {
$("#AppForm").html(data);
}
})
});
});
【问题讨论】:
-
为什么不使用@Ajax.BeginForm(...)
-
这就是我正在使用的 - 看看我的 _IOSAPP.cshtml。但是,当表单提交时,它会转到 Search 操作方法,如果模型无效,它只会显示部分视图。我想要的是整个页面(索引视图 + 有错误的部分视图)
-
我的意思是使用 Ajax.BeginForm 而不是 Html.BeginForm,所以提交时,转到搜索操作,如果有效,返回部分视图,搜索结果更新到页面,如果无效,返回部分视图错误消息更新到页面。sumbit 请求是一个 ajax 发布请求
标签: c# asp.net-mvc asp.net-mvc-4 razor asp.net-mvc-partialview