【发布时间】:2017-05-11 01:48:08
【问题描述】:
在我看来:
@foreach (var item in Model)
{
// some code
<form method="post" id="myForm" onsubmit="if (!onformsubmitContactUs()) { return false; }">
<input type="text" value="4" name="id" style="display: none;" />
<input type="text" name="Name" id="Name" placeholder="الاسم" required>
<textarea name="Msg" id="Msg" placeholder="تعليق" required></textarea>
<input type="submit" id="b" value="ارسال">
</form>
}
Ajax 函数:
<script type="text/javascript">
function onformsubmitContactUs() {
if ($('#Name').val() != '' && $('#Msg').val() != '') {
return true;
}
else {
if ($('#Name').val() == '') { $('#Name').css("borderColor", "red"); } else { $('#Name').css("borderColor", ""); }
if ($('#Msg').val() == '') { $('#Msg').css("borderColor", "red"); } else { $('#Msg').css("borderColor", ""); }
return false;
}
};
$(document).ready(function () {
$('#myForm').on('submit', function (event) {
event.preventDefault();
if (!onformsubmitContactUs()) return false;
$.ajax({
url: '@Url.Action("AddComment", "Home")',
type: 'post',
data: $('#myForm').serialize(),
beforeSend: function () {
$('#b').val('sending .......'); // change submit button text
$('#Name').css("borderColor", "");
$('#Msg').css("borderColor", "");
},
success: function (response,textStatus, jqXHR) {
// There is no problem with the validation
if (response) {
$('#b').val('success');
document.getElementById("myForm").reset();
$('#Name').css("borderColor", "");
$('#Msg').css("borderColor", "");
}
// Problem happend during the validation, display message related to the field.
$.each(data.Errors, function (key, value) {
if (value != null) {
//$("#Err_" + key).html(value[value.length - 1].ErrorMessage);
$("#" + key).css("borderColor", "rgba(247, 5, 5, 0.53)");
$('#b').html('send');
$('#result').text("");
}
});
}
});
});
});
</script>
动作控制器:
public bool AddComment()
{
bool result = false;
EventComment cuM = new EventComment();
string Name = Request.Form["Name"], Email = Request.Form["Email"],
Message = Request.Form["Msg"];
cuM.EventId = int.Parse(Request.Form["id"]);
cuM.Name = Name;
cuM.Comment = Message;
cuM.IsSeen = false;
cuM.IPAddress = Request.ServerVariables["REMOTE_ADDR"];
cuM.DateAdd = DateTime.Now;
cuM.Approval = false;
db.EventComments.Add(cuM);
db.SaveChanges();
result = true;
return result;
}
当提交我的表单在 foreach 循环中包含所有数据时,如果内容在循环后有 3 个表单,则 Form.Request 具有这样的所有数据:
{id=1,id=2,id=3,Name="00",Name="",Name="",Msg="",...}
什么错误。
如何让每个表单只使用其数据调用 ajax?
【问题讨论】:
标签: jquery ajax asp.net-mvc forms