//MVC HTML辅助类常用方法记录
(1)@Html.DisplayNameFor(model => model.Title)是显示列名,
(2)@Html.DisplayFor(modelItem => item.Title)是显示列的内容
(3)@Html.ActionLink("Create New", "Create")是超链接,跳转到model中的create页面,引用的是controller中create方法;
(4)@Html.ActionLink("Edit", "Edit", new { id=item.ID })编辑页面;
(5)@using (Html.BeginForm()) { @Html.ValidationSummary(true)}用于客户端验证,其Html.BeginForm()表示在本页显示
(6)<div class="editor-label">
@Html.LabelFor(model => model.Time)标签
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Time)编辑框
@Html.ValidationMessageFor(model => model.Time)验证合法性错误显示
</div>
/***************************************************/
/****MVC使用jQuery从视图向控制器传递Model的方法*****/
/***************************************************/
//Entity
using System.ComponentModel.DataAnnotations;
namespace MvcApplication1.Models
{
public class Movie
{
public int Id { get; set; }
[Required(ErrorMessage = "必填")]
public string Title { get; set; }
}
}
//Controller
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new Movie());
}
public ActionResult AddMovie(Movie movie)
{
return Json(new {msg = "ok"});
}
}
}
//View
@model MvcApplication1.Models.Movie
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
@using (Html.BeginForm("AddMovie", "Home", FormMethod.Post))
{
@Html.EditorFor(m => m.Title)
@Html.ValidationMessageFor(m => m.Title)
<br/>
<input type="button" id="addMovie" value="提交"/>
}
@section scripts
{
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script type="text/javascript">
$(function() {
$('#addMovie').click(function(e) {
//e.preventDefault();
if ($('form').valid()) {
$.ajax({
url: $('form').attr('action'),
type: $('form').attr('method'),
data: $('form').serialize(),
success: function(data) {
if (data.msg == 'ok') {
alert('提交成功');
}
}
});
}
});
});
</script>
}
/*=====================================
View新增商品
=====================================*/
@using System.Web.Optimization
@model MultiPageSimpleTask.Entitys.Product
@{
ViewBag.Title = "title";
Layout = null;
}
@Scripts.Render("~/Bundles/vendor/js/bottom")
<script type="text/javascript">
$(function() {
//新增商品
$("#addBtn")
.click(function() {
alert($('form').serialize());
$.ajax({
url: $('form').attr('action'),
type: $('form').attr('method'),
data: $('form').serialize(),
success: function(data) {
var result = data;
if (result.Status) {
alert("新增成功");
//top.window.location = '/Home/Index';
} else {
alert("新增失败\n" + result.Message);
}
}
});
});
});
</script>
<h2>title</h2>
@using (Html.BeginForm("add", "home", FormMethod.Post))
{
@Html.DisplayNameFor(m => m.ProductName)
@Html.TextBoxFor(m => m.ProductName,new { style = "width:100px;",@class="class1" })
<br/>
@Html.DisplayNameFor(m => m.Discontinued)
@Html.RadioButtonFor(m => m.Discontinued, true, new {@checked = true})
@Html.RadioButtonFor(m => m.Discontinued, false)
<br/>
<br/>
<input type="button" id="addBtn" value="新增商品"/>
}
/*=====================================
View修改商品
=====================================*/
@using System.Web.Optimization
@model MultiPageSimpleTask.Entitys.Product
@{
ViewBag.Title = "title";
Layout = null;
}
@Scripts.Render("~/Bundles/vendor/js/bottom")
<script type="text/javascript">
$(function() {
//修改商品
$("#updateBtn")
.click(function () {
alert($('form').serialize());
$.ajax({
url: $('form').attr('action'),
type: $('form').attr('method'),
data: $('form').serialize(),
success: function(data) {
var result = data;
if (result.Status) {
alert("修改成功");
//top.window.location = '/Home/Index';
} else {
alert("修改失败\n" + result.Message);
}
}
});
});
});
</script>
<h2>title</h2>
@using (Html.BeginForm("update", "home", FormMethod.Post))
{
@Html.DisplayNameFor(m => m.ProductName)
@Html.TextBoxFor(m => m.ProductName)
<br />
@Html.DisplayNameFor(m => m.Discontinued)
@Html.RadioButtonFor(m => m.Discontinued, true)
@Html.RadioButtonFor(m => m.Discontinued, false)
<br />
<br />
<input type="button" id="updateBtn" value="修改商品" />
}
/*=====================================
Controller控制器
=====================================*/
#region 新增商品
[HttpGet]
public ActionResult Add()
{
Entitys.Product product = new Entitys.Product();
return View(product);
}
[HttpPost]
public ActionResult Add(Entitys.Product model)
{
_result.Status = false;
//TODO:Convert to DTOs
if (!ModelState.IsValid)
{
_result.Message = ExpendErrors(this);
}
else
{
int i = _productAppService.InsertAndGetId(model); //新增
if (i > 0)
{
_result.Status = true;
}
}
return new JsonResult() { Data = _result };
}
#endregion
#region 修改商品
[HttpGet]
public ActionResult Update(int id)
{
var model = _productAppService.Get(id);
return View(model);
}
[HttpPost]
public ActionResult Update(Entitys.Product model)
{
_result.Status = false;
//TODO:Convert to DTOs
if (!ModelState.IsValid)
{
_result.Message = ExpendErrors(this);
}
else
{
var modelTarget = _productAppService.Get(model.Id); //赋值
modelTarget.ProductName = model.ProductName; //更新字段
modelTarget.Discontinued = model.Discontinued;
int i = _productAppService.InsertOrUpdateAndGetId(modelTarget); //新增
if (i > 0)
{
_result.Status = true;
}
}
return new JsonResult() { Data = _result };
}
#region 返回消息类
/// <summary>
/// 返回信息类
/// </summary>
public class StatusMsg
{
/// <summary>
/// 返回状态 true false
/// </summary>
public bool Status;
/// <summary>
/// 返回信息
/// </summary>
public string Message;
/// <summary>
/// 返回扩展信息 如400、401状态码
/// </summary>
public string Ext;
}
#endregion
#region 获取验证信息
public static string ExpendErrors(Controller controller)
{
System.Text.StringBuilder sbErrors = new System.Text.StringBuilder();
foreach (var item in controller.ModelState.Values)
{
if (item.Errors.Count > 0)
{
for (int i = item.Errors.Count - 1; i >= 0; i--)
{
sbErrors.AppendLine(item.Errors[i].ErrorMessage);
}
}
}
return sbErrors.ToString();
}
#endregion
}
#endregion
/*=====================================
Entity实体类数据
=====================================*/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Abp.Domain.Entities;
namespace MultiPageSimpleTask.Entitys
{
[Table("Product")]
public class Product : Entity
{
/// <summary>
/// ProductName
/// </summary>
[Display(Name = "商品名称")]
[Required(ErrorMessage= "商品名称不能为空")]
public virtual string ProductName { get; set; }
/// <summary>
/// SupplierID
/// </summary>
public virtual int? SupplierID { get; set; }
/// <summary>
/// CategoryID
/// </summary>
public virtual int? CategoryID { get; set; }
/// <summary>
/// QuantityPerUnit
/// </summary>
public virtual string QuantityPerUnit { get; set; }
/// <summary>
/// UnitPrice
/// </summary>
public virtual decimal? UnitPrice { get; set; }
/// <summary>
/// UnitsInStock
/// </summary>
public virtual Int16? UnitsInStock { get; set; }
/// <summary>
/// UnitsOnOrder
/// </summary>
public virtual Int16? UnitsOnOrder { get; set; }
/// <summary>
/// ReorderLevel
/// </summary>
public virtual Int16? ReorderLevel { get; set; }
/// <summary>
/// Discontinued
/// </summary>
[Display(Name = "发布状态")]
[Required(ErrorMessage="发布状态不能为空")]
public virtual bool? Discontinued { get; set; }
/* 示例
[StringLength(10, MinimumLength = 4, ErrorMessage = "{0}的长度必须大于{2}个字符并小于{1}个字符")]
[Display(Name = "密码")]
public virtual string LogPassword { get; set; }
[Display(Name = "确认密码")]
[Compare("LogPassword", ErrorMessage = "密码必须一致")]
public virtual string LogPasswordConfirm { get; set; }
[Display(Name = "姓名")]
public virtual string RealName { get; set; }
[Required]
[Display(Name = "登录账号")]
public virtual string LogID { get; set; }
[StringLength(10, MinimumLength = 4, ErrorMessage = "{0}的长度必须大于{2}个字符并小于{1}个字符")]
[Display(Name = "密码")]
public virtual string LogPassword { get; set; }
[StringLength(10, ErrorMessage = "{0}的长度不能大于{1}个字符")]
[Display(Name = "姓名")]
public virtual string RealName { get; set; }
[Display(Name = "出生日期")]
[Range(typeof(DateTime), "2011-12-31", "1950-1-1", ErrorMessage = "{0}的范围是{1}到{2}")]
public virtual DateTime Birthday { get; set; }
[RegularExpression(@"\d{17}[\d|X]|\d{15}", ErrorMessage = "{0}的格式不正确")]
[Display(Name = "身份证号码")]
public virtual string IdentityNo { get; set; }
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "{0}的格式不正确")]
[Display(Name = "邮箱")]
public virtual string Email { get; set; }
*/
}
}