【问题标题】:Model Validation With MVC Razor使用 MVC Razor 进行模型验证
【发布时间】:2015-08-12 12:32:05
【问题描述】:

我正在使用 Razor 引擎实现基于 MVC 的网站。

我已经在模型中创建了验证。 即学生验证是这样的:

[MetadataType(typeof(Student.StudentMetaData))]
public partial class Student
{
       internal sealed class StudentMetaData
       {
              [Required(ErrorMessageResourceName = "FirstNameRequired", ErrorMessageResourceType = typeof(StudentMessages))]
              public object FirstName { set; get; }

              [Required(ErrorMessageResourceName = "FatherNameRequired", ErrorMessageResourceType = typeof(StudentMessages))]
              public object FatherName { set; get; }
       }
}

学生已经实现了 IDataErrorInfo 接口。数据字段存在于其他分部类(T4文件创建的分部类)中。

问题是当我在Razor 视图中将它与客户端验证一起使用时:

@Html.TextBoxFor(m => m.FatherName, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.FatherName)

它没有收到我在资源文件中指定的消息。

我之前用 WPF 尝试过同样的技术,效果很好。

我允许在 Web.config 中进行客户端验证,并在我的视图中使用它:

@{
    HtmlHelper.ClientValidationEnabled = true;
}

【问题讨论】:

  • object 不是FirstNameFatherName 的合适类型。使用string
  • 你的类可能需要public 而不是internal,但是如果你使用视图模型并将验证属性应用于视图模型属性,你会发现这要容易得多
  • 对于给您带来的不便,我深表歉意。并感谢您的快速响应。我的部分类在不同的名称空间中存在的问题。
  • 附言。内部状态和对象类型都是正确的。
  • @WalidAshraf,我会删除这个问题。这对任何人都没有帮助。

标签: c# asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:
Add Name space in modal class in mvc.
using System.ComponentModel.DataAnnotations;

 public class TelePhones
    {      
        [Required (ErrorMessage  = "MobileNo is required")]
        public long MobileNo { get; set; }

        [DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
        [DataType(DataType.Date)]
        public string DateOfBirth { get; set; }

        [Range(15, 70, ErrorMessage = "Price must be between 15 and 70")]
        public int Age { get; set; }
}
client side validation in mvc

 <div class="editor-label">
            @Html.LabelFor(model => model.MobileNo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.MobileNo)
            @Html.ValidationMessageFor(model => model.MobileNo)
        </div> 
        <div class="editor-label">
            @Html.LabelFor(model => model.DateOfBirth)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DateOfBirth)
            @Html.ValidationMessageFor(model => model.DateOfBirth)       
       </div> 
        <div class="editor-label">
            @Html.LabelFor(model => model.Age)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Age)
            @Html.ValidationMessageFor(model => model.Age)
        </div>

【讨论】:

    猜你喜欢
    • 2018-06-10
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多