ASP MVC模型验证不在视图中工作

时间:2014-05-16 17:28:12

标签: c# regex asp.net-mvc asp.net-mvc-3 razor

以下是我在ASP MVC 3站点中设置的模型验证。我想强制执行characer限制并防止输入非字母数字字符。

然而..这里的验证都没有效果。每次我输入$#@或超过字符限制时,表单仍然会回发给控制器。

只有第二次/第三次使用正则表达式所以不确定我是否做错了。任何帮助将不胜感激。感谢

模型

[MetadataType(typeof(ChannelMetaData))]
public partial class Channel1
{
    public IEnumerable<SelectListItem> Status { get; set; } 
}
class ChannelMetaData
{
    [Required(ErrorMessage = "Channel Code required")]
    [DisplayName("Channel Code")]
    [StringLength(1)]
    [RegularExpression("^[a-zA-Z0-9_]*$", ErrorMessage = "Invalid Channel Code")]
    public string ChannelCode { get; set; }

    [DisplayName("Channel Short Description")]
    [Required(ErrorMessage = "Channel Short Description required")]
    [StringLength(10)]
    [RegularExpression("^[a-zA-Z0-9_]*$", ErrorMessage = "Invalid Channel Short Description")]
    public string ChannelDescription { get; set; }

    [DisplayName("Channel Long Description")]
    [Required(ErrorMessage = "Channel Long Description required")]
    [StringLength(30)]
    [RegularExpression("^[a-zA-Z0-9_]*$", ErrorMessage = "Invalid Channel Long Description")]
    public string ChannelLongDescription { get; set; }

    [DisplayName("Status")]
    public string Status { get; set; }
}

查看

@using System.Collections.Specialized
@model IEnumerable<Monet.Models.Channel>

@{
    ViewBag.Title = "EditChannels";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>EditChannels</h2>

@using(Html.BeginForm("EditChannels", "ZipCodeTerritory", FormMethod.Post))
{
    <table>
        <thead>
            <th>Channel Code</th>
            <th>Channel Description</th>
            <th>Channel Long Description</th>
            <th>Status</th>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    @Html.HiddenFor(model => item.Id)
                    <td>
                        <center>
                            @Html.TextBoxFor(model => item.ChannelCode, new { style="width:10px;" })
                            @Html.ValidationMessageFor(model => item.ChannelCode)                            
                        </center>
                    </td>
                    <td>
                        @Html.TextBoxFor(model => item.ChannelDescription, new { maxlength = 10 })
                        @Html.ValidationMessageFor(model => item.ChannelDescription)
                    </td>
                    <td>
                        @Html.TextBoxFor(model => item.ChannelLongDescription, new { maxlength = 30 })
                        @Html.ValidationMessageFor(model => item.ChannelLongDescription)
                    </td>
                    <td>
                        @Html.DropDownListFor(model => item.Status, new SelectList(
                                                                        new List<Object>
                                                                            {
                                                                                new {value = "A", text = "A"},
                                                                                new {value = "I", text = "I"}
                                                                            }, "value", "text", item.Status))
                    </td>
                </tr>
            }
            <input type="submit" name="Save"/>
            @Html.Raw("&nbsp;&nbsp;|&nbsp;&nbsp;")
            @Html.ActionLink("Create New", "CreateChannel", "ZipCodeTerritory")
        </tbody>
    </table>
}

控制器

    [HttpPost]
    public ActionResult EditChannels(IEnumerable<Channel> channels)
    {
        if (ModelState.IsValid)
        {
            foreach (Channel item in channels)
            {
                db.Entry(item).State = EntityState.Modified;
                db.SaveChanges();
            }                
        }
        else
        {
            return View(channels);
        }

        return RedirectToAction("Index");
    }

修改

下面的答案我已将以下脚本添加到Layout.cshtml文件的底部。

    <script src="@Url.Content("~/Scripts/jquery-unobtrustive-ajax.js")" type="text/javascript"></script> 
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>    
    <script src="@Url.Content("~/Scripts/jquery-ui.js")" type="text/javascript"></script>     
    </body>
</html>

4 个答案:

答案 0 :(得分:3)

您是否按正确顺序加载js文件? 我过去遇到过这个问题并解决了js文件的加载顺序。 尝试按以下顺序加载js文件:

  • jquery库(在head标签内加载此文件)

在/ body标记

之前将以下文件放在html(或cshtml)的末尾
  • jquery.unobtrusive-AJAX
  • jquery.validate
  • jquery.validate.unobtrusive
  • 的jquery-UI- {版本}的.js
  • jquery.blockUI.js

答案 1 :(得分:2)

使用for循环,因此您可以直接将属性与模型相关联:

@for(int i = 0; i < Model.Count; i++)
{
     <tr>
        @Html.HiddenFor(model => model[i].Id)
        <td>
            <center>
                @Html.TextBoxFor(model => model[i].ChannelCode, new { style="width:10px;" })                  
                @Html.ValidationMessageFor(model => model[i].ChannelCode)                            
             </center>
        </td>

     //etc..
}

当您使用@Html.HiddenFor(model => item.Id)时,您正在失去&#39;连接&#39; (有人请更正我的术语)回到模型

答案 2 :(得分:2)

您分配了元数据的部分类称为Channel1

[MetadataType(typeof(ChannelMetaData))]
public partial class Channel1
{
    public IEnumerable<SelectListItem> Status { get; set; } 
}

但你绑定的模型是频道

public ActionResult EditChannels(IEnumerable<**Channel**> channels)

答案 3 :(得分:1)

这最终是本节中一个简单的拼写错误的结果

[MetadataType(typeof(ChannelMetaData))]
public partial class Channel1
{
    public IEnumerable<SelectListItem> Status { get; set; } 
}

部分班级名称必须为Channel,而不是Channel1