@model MVC_STORE.Models.Product
@{
Layout = null;
}
<!DOCTYPE html>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>AddProduct</title>
</head>
<body>
<div>
<form id="formAdd" onsubmit=" return SendData(); return false;">
<table>
<tr>
<td>Serial number:</td>
<td>@Html.TextBoxFor(m => m.SerialNo) @Html.ValidationMessageFor(m => m.SerialNo)</td>
</tr>
<tr>
<td>Product name:</td>
<td>@Html.TextBoxFor(m => m.Name) @Html.ValidationMessageFor(m => m.Name)</td>
</tr>
<tr>
<td>Product price:</td>
<td>@Html.TextBoxFor(m => m.Price) @Html.ValidationMessageFor(m => m.Price)</td>
</tr>
<tr>
<td>Product quatity:</td>
<td>@Html.TextBoxFor(m => m.Quatity) @Html.ValidationMessageFor(m => m.Quatity)</td>
</tr>
</table>
<input type="submit" id="toAdd" value="Add product" />
</form>
@Html.Partial("ProductsTable")
<script language="javascript">
function SendData() {
$("#status").text("Saving product, please wait..");
var formData = $("#formAdd").serialize();
$.post("addProduct", formData, BindData);
$("#status").text("");
}
</script>
</div>
</body>
</html>
onsubmit出于某种原因无法正常工作,我已经阅读了很多有关它的文章,但是在这种情况下,没有人帮助我。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace HW_MVC_STORE.Models
{
public class Product
{
[Key]
[RegularExpression("^[a-zA-Z0-9]+$", ErrorMessage = "Only upper- and lower- case letters and numbers.")]
[Required]
[StringLength(5,MinimumLength=5, ErrorMessage = "Please enter 5 characters serial.")]
public string SerialNo { get; set; }
[RegularExpression("^[a-zA-Z]+$", ErrorMessage = "Only upper- and lower- case letters")]
[Required]
[StringLength(10, MinimumLength=2, ErrorMessage="Please enter between 2 and 10 characters.")]
public string Name { get; set; }
[RegularExpression("^[0-9]+$", ErrorMessage = "Integers only")]
[Required]
public string Quatity { get; set; }
[RegularExpression("^([0-9]+[.][0-9]+)|([1-9]+[0-9]*)$", ErrorMessage = "Numbers only, bigger then zero")]
[Required]
public string Price { get; set; }
}
}
我已经尝试了帖子中的一些建议,但是都没有用。
<form id="formAdd" onsubmit="return SendData(); return false;">
<form id="formAdd" onsubmit="return SendData();">
<form id="formAdd" onsubmit="SendData()">
我不明白为什么它甚至调用了SendData()函数,它不打算在所有文本框都正确归档之前就离开表单。
我该如何解决它,或者至少有什么问题呢?
最佳答案
你需要:
<form id="formAdd" onsubmit="SendData(); return false;">
函数
SendData
不返回值,因此return SendData();
没有意义。不返回false会导致页面重新加载(默认操作)
如果
SendData
中的ajax POST无法正常工作,我们需要更多有关此细节。