我的表格中有这样的代码
@foreach (var option in Model.Options)
{
@Html.Action("GetQuestionOption", new { optionId = option.Id })
}
这是控制器和局部视图
public ActionResult GetQuestionOption(int? optionId = null)
{
var option = optionId.HasValue ? UnitOfWork.OptionRepository.GetById(optionId.Value) : new QuestionOption();
return PartialView("_Option", option);
}
部分视图
@model QuestionOption
<div class="option-box">
@Html.HiddenFor(model => model.Id)
<div>
@Html.TextBoxFor(model => model.OptionText)
</div>
<div>
@Html.ValidationMessageFor(model => model.OptionText)
</div>
</div>
但是,当我提交表单时,此数据不会发布到服务器,而选项始终为null。我想这不会映射到选项。我怎样才能使这个工作?
P.S。我也在那里用javascript添加选项
$.ajax({
type: "POST",
url: "/Contr/GetQuestionOption",
success: function (data) {
$("#options").append(data);
}
});
答案 0 :(得分:0)
您的部分视图,您必须在Form中放置字段,并提供Id
@model QuestionOption
@using (Html.BeginForm("GetQuestionOption", "YourControllerName", FormMethod.Post, new { id = "myId" }))
{
<div class="option-box">
@Html.HiddenFor(model => model.Id)
<div>
@Html.TextBoxFor(model => model.OptionText)
</div>
<div>
@Html.ValidationMessageFor(model => model.OptionText)
</div>
</div>
<input id="postForm" type="submit" value="Save" class="btn btn-primary pull-right" />
}
Ajax请求:
$('#postForm').click(function(e){
e.preventDefault();
$.ajax({
data: $('#myId').serialize(),
type: "POST",
url: "/Contr/GetQuestionOption",
success: function (data) {
$("#options").append(data);
}
});
});