Mvc form提交
在项目开发中,我们离不开表单提交,本篇主要记录mvc的Ajax.BeginForm提交方式。
- 需要用到的js
@Url.Script("~/Content/Scripts/jquery-1.7.1.js")
@Url.Script("~/Content/Scripts/jquery.validate.min.js")
@Url.Script("~/Content/Scripts/jquery.validate.unobtrusive.min.js")
@Url.Script("~/Content/Scripts/jquery.unobtrusive-ajax.min.js")
- 表单
@using (Ajax.BeginForm("EditUser", "UserCenter", new AjaxOptions { Url = Url.Action("EditUser"), HttpMethod = "POST", OnSuccess = "ajaxForm" }, new { id = "editeForm" }))
{
@Html.AntiForgeryToken()
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td width="13%" align="right">
@Html.LabelFor(model => model.nickname):
</td>
<td width="87%">
@Html.TextBoxFor(model => model.nickname, new { @class = "input1" })
@Html.ValidationMessageFor(model => model.nickname)
<span class="red ml10">*</span>
<span class="f12 cGray">必填</span>
</td>
</tr>
<tr>
<td align="right">
@Html.LabelFor(model => model.email):
</td>
<td id="td_email">
@{
if (Model != null)
{
if (string.IsNullOrEmpty(Model.email))
{
<font class="red">未绑定邮箱 </font> <a href="javascript:void(0)" onclick="triggerLi(3)"
class="cBlue f12 ml10"> 马上去绑定</a>
}
else if (Model.email_verified == 0)
{
@Html.Raw(Model.email)
<font class="red">未验证</font> <a href="javascript:void(0)" onclick="triggerLi(3)"
class="cBlue f12 ml10">马上去验证</a>
}
else
{
@Html.Raw(Model.email) <span>已绑定</span>
}
}
}
</td>
</tr>
<tr>
<td align="right">
@Html.LabelFor(model => model.mobile):
</td>
<td id="td_mobile">
@{
if (Model != null)
{
if (string.IsNullOrEmpty(Model.mobile))
{
<font class="red">未绑定手机 </font> <a href="javascript:void(0)" onclick="triggerLi(4)"
class="cBlue f12 ml10"> 马上去绑定</a>}
else if (Model.mobile_verified == 0)
{
@Html.Label(Model.mobile)
<font class="red">未验证</font> <a href="javascript:void(0)" onclick="triggerLi(4)"
class="cBlue f12 ml10">马上去验证</a>
}
else
{
@Model.mobile <span>已验证</span>
}
}
}
</td>
</tr>
<tr>
<td align="right">
@Html.LabelFor(model => model.qq):
</td>
<td>
@Html.TextBoxFor(model => model.qq, new { @class = "input1" })
@Html.ValidationMessageFor(model => model.qq)
</td>
</tr>
<tr>
<td align="right">
@Html.LabelFor(model => model.sex):
</td>
<td>
@{ Collection<CodeDescription> sex = ViewBag.Sex as Collection<CodeDescription>;}
@Html.RadioButtonListFor(model => model.sex, sex, System.Web.UI.WebControls.RepeatDirection.Horizontal)
@Html.ValidationMessageFor(model => model.sex)
</td>
</tr>
<tr>
<td align="right">
@Html.LabelFor(model => model.birthday):
</td>
<td>
@Html.TextBoxFor(model => model.birthday, new { @class = "Wdate", onClick = "WdatePicker()" })
@Html.ValidationMessageFor(model => model.birthday)
</td>
<tr>
<td align="right">
@Html.LabelFor(model => model.province_id):
</td>
<td>
@Html.HiddenFor(model => model.province_id)
@Html.HiddenFor(model => model.city_id)
<span id="span_province"></span><span id="span_city" style="margin-left: 10px"></span>
@*@Html.EditorFor(model => model.Address)
@Html.ValidationMessageFor(model => model.Address)*@
</td>
</tr>
<tr>
<td align="right">
@Html.LabelFor(model => model.job):
</td>
<td>
@{
Collection<CodeDescription> Vocation = ViewBag.Vocation as Collection<CodeDescription>;}
@Html.RadioButtonListFor(model => model.job, Vocation, System.Web.UI.WebControls.RepeatDirection.Horizontal)
@Html.ValidationMessageFor(model => model.job)
</td>
</tr>
<tr class="bg">
<td valign="top" align="right">
@Html.LabelFor(model => model.trade_style):
</td>
<td>
@{
Collection<CodeDescription> InvestmentStyle = ViewBag.InvestmentStyle as Collection<CodeDescription>;}
@Html.RadioButtonListFor(model => model.trade_style, InvestmentStyle, System.Web.UI.WebControls.RepeatDirection.Horizontal)
@Html.ValidationMessageFor(model => model.trade_style)
</td>
</tr>
<tr class="bg">
<td class="pb10" valign="top" align="right">
@Html.LabelFor(model => model.trade_begin):
</td>
<td class="pb10">
@{
List<SelectListItem> dorpDownList = new List<SelectListItem>();
for (int year = 1990; year < DateTime.Now.Year; year++)
{
SelectListItem selectListItem = new SelectListItem();
if (Model != null && Model.trade_begin == year)
{
selectListItem.Selected = true;
}
selectListItem.Text = year.ToString();
selectListItem.Value = year.ToString();
dorpDownList.Add(selectListItem);
}
}
@Html.DropDownListFor(model => model.trade_begin, dorpDownList) 年
@Html.ValidationMessageFor(model => model.trade_begin)
</td>
</tr>
<tr>
<td class="tc" colspan="2">
<input class="btn" value="提交修改" type="submit" name="">
</td>
</tr>
</tbody>
</table>
}
表单中的用户昵称采用
[Required(ErrorMessage = "请输入昵称")]
[Remote("UniqueNickCheck", "Account", ErrorMessage = "昵称已存在", HttpMethod = "post")]
[StringLength(8, MinimumLength = 2, ErrorMessage = "长度介于2-8位")]
[Display(Name = "昵称")]
public string nickname { get; set; }
配置验证唯一性。
- 实体
public class UserInfo
{
public int ret { set; get; }
public string msg { set; get; }
/// <summary>
/// 用户编号
/// </summary>
[ScaffoldColumn(false)]
public string userid { set; get; }
/// <summary>
/// 用户名
/// </summary>
[ScaffoldColumn(false)]
public string username { set; get; }
[Required(ErrorMessage = "请输入昵称")]
[Remote("UniqueNickCheck", "Account", ErrorMessage = "昵称已存在", HttpMethod = "post")]
[StringLength(8, MinimumLength = 2, ErrorMessage = "长度介于2-8位")]
[Display(Name = "昵称")]
public string nickname { get; set; }
/// <summary>
/// 头像地址
/// </summary>
[ScaffoldColumn(false)]
public string userimg { get; set; }
private string _mobile = "";
/// <summary>
/// 手机号
/// </summary>
[Display(Name = "手机")]
[RegularExpression(@"^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$", ErrorMessage = "手机号码格式错误")]
[Editable(false)]
public string mobile
{
get { return _mobile; }
set { _mobile = value; }
}
/// <summary>
/// 手机号是否已验证 0:未验证 1:已验证
/// </summary>
[ScaffoldColumn(false)]
public int mobile_verified { get; set; }
/// <summary>
/// 邮箱地址
/// </summary>
private string _email = "";
[Display(Name = "邮箱")]
[DataType(DataType.EmailAddress)]
[Editable(false)]
public string email
{
get { return _email; }
set { _email = value; }
}
/// <summary>
/// 邮箱是否已验证 0:未验证 1:已验证
/// </summary>
[ScaffoldColumn(false)]
public int email_verified { get; set; }
/// <summary>
/// 性别 0:未填 1:男 2:女
/// </summary>
[Display(Name = "性别")]
public int sex { get; set; }
/// <summary>
/// 出生年月
/// </summary>
[Display(Name = "生日")]
[RegularExpression(@"^((?:19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$", ErrorMessage = "日期格式为yyyy-MM-dd")]
public string birthday { get; set; }
[Display(Name = "QQ")]
[StringLength(20,MinimumLength=1,ErrorMessage="长度为1-20")]
[RegularExpression(@"^\d{1,20}$", ErrorMessage = "QQ号码为1-20位数字")]
public string qq { get; set; }
/// <summary>
/// 所在省/直辖市区号
/// </summary>
[Display(Name = "现居地址")]
public string province_id { get; set; }
/// <summary>
/// 所在城市区号
/// </summary>
public string city_id { get; set; }
/// <summary>
/// 职业
/// </summary>
[Display(Name = "职业")]
public sbyte? job { get; set; }
/// <summary>
/// 投资风格
/// </summary>
[Display(Name = "投资风格")]
public sbyte? trade_style { get; set; }
/// <summary>
/// 入市时间(年份)
/// </summary>
[Display(Name = "入市时间")]
public int? trade_begin { get; set; }
/// <summary>
/// 用户角色
/// </summary>
[ScaffoldColumn(false)]
public sbyte? userrole { get; set; }
/// <summary>
/// 用户开通的直播室编号
/// </summary>
[ScaffoldColumn(false)]
public int? cast_room_id { get; set; }
}
- 相关js
window.ajaxForm= function (data ) {
if (data.success) {
var infoqq=$.trim($("#@Html.NameFor(model => model.qq)").val());
if(infoqq=="")
$("#@Html.NameFor(model => model.qq)").val(qq);
art.dialog.tips(data.Message, showtime);
} else {
$(".error").remove();
if(typeof(data)=="string")
window.location.href = "@FormsAuthentication.LoginUrl";
else if (data.returnUrl) window.location.href = data.returnUrl;
else if(data.controlID){
var $err=$("<label generated=\"true\" class=\"error\"></label>");
$err.insertAfter($("#"+data.controlID)).html(data.Message);
}
else art.dialog.tips(data.Message, showtime);
}
}
数据验证js插件 validate使用格式
$("#fromVCode").validate({
rules: {
validatecode: {
required: true,
maxlength: 6
}
},
highlight: false,
errorPlacement: function(error, element) {
element.next().next("div").empty();
error.appendTo(element.next().next("div"));
},
success: function(label) {
label.remove();
},
submitHandler: function(form) {
var $err=$("<label generated=\"true\" class=\"error\"></label>");
$("#btnValidatecode").attr("disabled", "disabled");
if($("#confirmphone").val()=="")
{
$("#confirmphone").next().next("div").empty();
$err.appendTo($("#confirmphone").next().next("div")).html("请输入手机号!");
("#btnValidatecode").removeAttr("disabled");
return false;
}
var par=$(form).serialize()+"&mobile="+$("#confirmphone").val();
$.post("@Url.Action("ValidateCode", "UserCenter")", par,
function(data) {
if (data.success) {
$(form)[0].reset();
$("#td_mobile").html($("#confirmphone").val()+"<span>已验证</span>");
art.dialog.tips(data.Message, showtime);
} else {
if(typeof(data)=="string")
window.location.href = "@FormsAuthentication.LoginUrl";
else if (data.returnUrl) window.location.href = data.returnUrl;
else art.dialog.tips(data.Message, showtime);
}
$("#btnValidatecode").removeAttr("disabled");
});
return false;
}
});