我正在尝试在主(索引)视图中显示部分视图:
步骤:
我遇到了数字4的问题,因为当搜索表单提交时,它只会在新窗口中显示部分视图。我想显示整个页面:索引视图+部分视图有错误。
连连呢?这就是我所拥有的:
图像
控制器
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"});
}
}
Index.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);
}
})
});
});
答案 0 :(得分:1)
你也需要通过ajax调用搜索方法。
更改index.html然后
1-如果Form有效则替换整个html或mainContainer(我已添加到视图中的div)。
2-否则只需替换局部视图。
@{ ViewBag.Title = "App Selection"; }
<div id="mainContainer">
<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
</div>
从部分视图中删除表单标记只需调用ajax调用方法进行搜索。 处理此问题的最简单方法是使用 MVC unobtrusive ajax 。
答案 1 :(得分:1)
我想说使用内联Ajax来提交此表单。
@using (Html.BeginForm("Search", "App"))
{
@Html.Label("App Name:")
@Html.TextBoxFor(x => x.IOSAppName)
<input id="btnIOS" type="submit" value="Search IOS App" />
}
将上面给定的代码更改为以下代码
@using (
Ajax.BeginForm(
"Form", "App",
new AjaxOptions()
{
UpdateTargetId = "App",
HttpMethod = "Post"
}
)
)
{
<div class="editor-label">
@Html.Label("App Name:")
</div>
<div class="editor-field">
@Html.TextBoxFor(x => x.IOSAppName)
</div>
<input id="btnIOS" type="submit" value="Search IOS App" />
}
//in controller change the parameter of the given method from string type to model object which will be posted by ajax form.
public ActionResult Form(AppModel appModel)
{
if (appModel.type == "IOS")
return PartialView("_IOSApp", new AppModel());
else
return PartialView("_AndroidApp", new AppModel());
}