我有一個Web應用程序,我想在其中顯示測試對象的表單。不同的測試實例可以有不同的模式。我可以很好地顯示它,但它不會將表單中的所有數據填充到我的模型中。爲什麼MVC 2中的ViewModel子對象爲空?
這裏是我的模型類:
public class EnterTestData
{
public string StudyId { get; set; }
public Test Test { get; set; }
}
public sealed class Test
{
public string Identity { get; set; }
public string Name { get; set; }
public IEnumerable<TestField> Fields { get; set; }
}
public sealed class TestField
{
public string Identity { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public string Type { get; set; }
}
這裏是我查看相關部分:
<% Html.BeginForm("PostTestData", "StudiesUserInterface"); %>
<table>
<%
foreach (var testField in Model.Test.Fields)
Html.RenderPartial("UserControls/TestFieldUserControlascx", testField);
foreach (var category in Model.Test.Categories)
{
%>
<tr>
<td colspan="2" style="font-style: italic; text-align: center;">
<%=category.Name %>
</td>
</tr>
<%
foreach (var testField in category.Fields)
Html.RenderPartial("UserControls/TestFieldUserControlascx", testField);
}
%>
<tr>
<td colspan="2" style="text-align: right;">
<input type="submit" name="newsletter" value="Enter Result" />
</td>
</tr>
</table>
<% Html.EndForm(); %>
而對於實際的文本框的局部視圖:
<tr>
<td>
<%= Model.Name %>
</td>
<td>
<%
switch (Model.Type)
{
case "date":
case "text":
case "number":
%>
<%= Html.TextBox(Model.name, Model.Value) %>
<% break;
default: %><%= Html.Label("Unknown data type") %><% break;
}
%>
</td>
</tr>
更新控制器方法:
public ActionResult EnterTestData(string studyId, string testId)
{
var testDefinition = ServiceKitLocator.GetStudyService().GetTestDefinition(testId);
return View(new EnterTestData { StudyId = studyId, Test = testDefinition });
}
public ActionResult PostTestData(EnterTestData model)
{
//I'm just putting a break point here and checking the model in the debugger for now
return RedirectToAction("Index");
}
問題是,Test
返回到我的控制器時爲空。我如何獲得它填充?爲什麼它是空的?
您是否也可以顯示您的控制器操作方法? – Sampath
完成。另外,我意識到我的部分視圖中的TextBox定義不好,所以我也更新了它。 – tallseth
作爲一種最佳實踐,您總是嘗試爲您的操作方法提供[HttpGet]或[HttpPost]。要了解哪個是獲取和發佈的內容非常困難。 – Sampath