Asp.Net - MVC-5.模型绑定与验证

使用模型获取绑定数据:

 [RegularExpression]约束邮箱规范使用.

多行文本框;

  <p>评论:@Html.TextArea("desc",null,5,30,null)</p>

 Person类;

 public class Person
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string Num { get; set; }
    }
<body>
    <h1>个人信息</h1>
    @using (Html.BeginForm())
    {
    <table>
        <tr>
            <th>ID</th>
            <td>@Html.TextBox("id")</td>
        </tr>
        <tr>
            <th>Name</th>
            <td>@Html.TextBox("name")</td>
        </tr>
        <tr>
            <th>Num</th>
            <td>@Html.TextBox("num")</td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" name="name" value="提交" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <strong>
                    @ViewBag.msg
                </strong>
            </td>
        </tr>
    </table>
    }
</body>
 [HttpPost]
//Person是文件里新建的一个类。
        public ActionResult Index(Person p)

        {
            ViewBag.msg = "商品编号是: " + p.ID  + "  商品名称是: " + p.Name + "  商品数量是: " + p.Num;
            return View();
        }

 运行结果:

模型验证:

public class Movie
    {
        [DisplayName("影片名称")]
        [Required(ErrorMessage = "{0}不能为空")]
        public string Name { get; set; }
        [DisplayName("上映日期")]
        [DataType(DataType.Date, ErrorMessage = "{0}的日期格式不对")]
        public DateTime ReleaseDate { get; set; }
        [DisplayName("光盘价格")]
        [Range(1, 100, ErrorMessage = "{0}必须在1-100之间")]
        public decimal Price { get; set; }
        [DisplayName("评分")]
        [StringLength(10, ErrorMessage = "{0}必须在10个字以内")]
     
        public string Rating { get; set; }



 [RegularExpression("^\\s*([A-Za-z0-9_-]+(\\.\\w+)*@(\\w+\\.)+\\w{2,5})\\s*$", ErrorMessage ="{0}邮箱格式不正确")]
        public string userEmail { get; set; }
    }

前端增加一条代码: @Html.ValidationSummary()。

 <tr>
                <td></td>
                <td>
                    <input type="submit" value="新增影片" />
                    @Html.ValidationSummary()
                    @ViewBag.Info
                </td>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞鹰@四海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值