首先我必須說這個我是新來的MVC4和開發這個應用程序和學習MVC4同時:)。MVC4:將子部分視圖值發送給控制器?
在此應用程式, 下面是其中3的局部視圖被呈現也有一個按鈕父視圖:
[code]
<td id="track">@Html.Partial("_Track",Model)</td><br>
<td id="tech">
<div id="Technologies"> @Html.Partial("_Technology",Model)
</div></td></tr>
..
[some code]
..
<td class="subtopic">
<div class="subtopiclist" id="subque">@Html.Partial("_Subtopics",Model)</div><br>
<input type="Submit" value="Fetch Interview Questions" name="Fetch" id="Fetch" />
</td>
局部視圖1(它包含下拉列表):
@model MvcApplication3.Models.CommonWrapper
@using (Ajax.BeginForm("SelectTrack", "Home", new AjaxOptions { UpdateTargetId = "Technologies" }))
{
@Html.DropDownListFor(
m=>m.SelectedTrackId,
new SelectList(Model.track, "TrackId", "TrackName"),
string.Empty
)
}
<script type="text/javascript">
$('#SelectedTrackId').change(function() {
$(this).parents('form').submit();
});
</script>
Parital View2(它包含下拉列表):
@model MvcApplication3.Models.CommonWrapper
@if (Model.tech != null && Model.tech.Count() > 0)
{
using (Ajax.BeginForm("SelectTechnology", "Home", new AjaxOptions { UpdateTargetId = "subque" }))
{
@Html.HiddenFor(m => m.SelectedTrackId)
@Html.DropDownListFor(
m => m.SelectedTechId,
new SelectList(Model.tech, "TechId", "TechName"),
string.Empty
)
}
}
<script type="text/javascript">
$(document).on('change', '#SelectedTechId', function() {
$(this).parents('form').submit();
});
</script>
局部視圖3(它含有多個複選框):
@if (Model.subtopic != null && Model.subtopic.Count() > 0)
{
<table>
@for (int i = 0; i < Model.subtopic.Count; i++)
{
<tr><td>
@Html.CheckBoxFor(m => m.subtopic[i].IsSelected, new { id = "subTopic_" + i })
@Html.HiddenFor(m => m.subtopic[i].SubtopicName)
@Html.DisplayFor(m => m.subtopic[i].SubtopicName)
<td>
</tr>
}
</table>
}
現在在父視圖,我要取這三個部分views.Also的值,我需要發送這些讀取值提供給控制器。
如何做到這一點?任何人都可以幫助我解決這個問題。
在此先感謝
新增控制器代碼:
[HttpPost]
public ActionResult SelectTrack(int? selectedTrackId)
{
CommonWrapper wrapper = new CommonWrapper();
wrapper.tech = new List<TechModel>();
if (selectedTrackId.HasValue)
{
wrapper.tech = (from s in CommonWrapper.GetTechnology()
where s.TrackId == selectedTrackId
orderby s.TechName
select s).ToList();
}
return PartialView("_Technology", wrapper);
}
[HttpPost]
public ActionResult SelectTechnology(int? selectedTechId)
{
CommonWrapper wrapper = new CommonWrapper();
wrapper.subtopic = new List<SubtopicsModel>();
if (selectedTechId.HasValue)
{
wrapper.subtopic = (from s in CommonWrapper.GetSubtopics()
where s.TechId == selectedTechId
orderby s.SubtopicName
select s).ToList();
}
return PartialView("_Subtopics", wrapper);
}
這一切都不是魔術(只是有點模糊)。首先查看你的輸出HTML頁面,你會看到表單和輸入是如何構建的(就像一個正常的單個表單有很多字段一樣)。 **一個問題是,當你想要在父視圖中使用單個表單時,你在表單視圖上嵌套表單。**當你正在爲數組正確使用索引時,它大部分都會綁定到接收到的模型'as-is'。請顯示您的控制器代碼。 –
嗨TrueBlueAussie我添加了控制器代碼。 – user3240292