我有这样的表格:
@model project.Models.ChannelAndLocationViewModel
@{
const string formId = "parentForm";
}
@using (Html.BeginForm("EditChannel", "Channel", FormMethod.Post, new { id = formId }))
{
Html.RenderPartial("EditChannelForm", Model);
<br /><br />
<!--<input type="submit" value="Save"/>-->
<input type="button" value="Save" onclick="editChannel('@Model.ChannelViewModel.ID', @formId)" />
}
我试图在JS代码中提交此表单,如下所示:
function editChannel(channelId, parentForm) {
$(parentForm).submit();
$.ajax({
url: '/Channel/EditChannel/',
type: "POST",
cache: false,
data: {
id: channelId
},
success: function (msg) {
alert("Msg: " + msg);
if (msg === "ChangeOfSensitiveData") {
showAlertOnChangeOfSensitiveData('sensitivDataMsgDiv');
} else {
alert("Else");
}
},
error: function (msg) {
showDialog('errorDiv');
}
});
}
但似乎表单永远不会被提交,因为模型没有被解析为控制器。一旦调用Action方法,该模型为null。行动如下:
[HttpPost]
public ActionResult EditChannel(int id, ChannelAndLocationViewModel updatedModel)
{ ...}
如何从JS文件提交表单?
答案 0 :(得分:2)
该模型为空,因为它尚未添加到数据中。尝试:
data: {
id: channelId,
updatedModel : { ...... }
},
答案 1 :(得分:1)
这样做:
function editChannel(channelId, parentForm) {
$("#formId").submit(function(event) {
event.preventDefault();
$.ajax({
url: '/Channel/EditChannel/',
type: "POST",
cache: false,
data: {
id: channelId,
updatedModel: parentForm
},
success: function (msg) {
alert("Msg: " + msg);
if (msg === "ChangeOfSensitiveData") {
showAlertOnChangeOfSensitiveData('sensitivDataMsgDiv');
} else {
alert("Else");
}
},
error: function (msg) {
showDialog('errorDiv');
}
});
});
}