c# - 注释验证在 ASP .net MVC 中不起作用

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

我正在开发一个 ASP .net MVC 项目,在该项目中我使用了数据注释验证器,但它无法正常工作。我是 MVC 的新手。请帮助我

我的模型

 public class Home
    {
        public int i;

        [Required(ErrorMessage="Please enter")]
        [StringLength(160)]
        public string name;
    }

我的 Controller

public ActionResult Index()
    {
        Home h = new Home();
        return View(h);

    }

    [HttpPost]
    public ActionResult Index(Home h)
    {
        if (ModelState.IsValid)
        {
            return RedirectToAction("Success");
        }
        //ModelState.AddModelError("name", "Enter  name");
        return View(h);
    }

我的观点

@using (Html.BeginForm())
{

    <label for="name">Name: </label>
    @Html.TextBoxFor(m=>m.name)


    @Html.ValidationMessageFor(m=>m.name)


    <input type="submit" value="Register" />
}

最佳答案

要使 DataAnnotation 起作用,您需要定义属性。所以你需要有 get;设置;

[Required(ErrorMessage="Please enter")]
[StringLength(160)]
public string name { get; set; }

关于c# - 注释验证在 ASP .net MVC 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34588090/

相关文章:

c# - 当用户从 DropDownList 中选择不同选项时如何更改内容

asp.net - 有没有人在 ASP.Net 网站上使用 OrientDB

c# - 为什么我们使用@Master类型?

c# - 如何在 ASP.NET MVC 上同时执行 Azure Active Directory 单点登录和表单例份验证

html - 使 Bootstrap 选项卡在 MVC 操作上处于事件状态

c# - 在 Entity Framework Core 中包含子属性

c# - 加载资源: 403 forbidden with . js优化失败

c# - IAsyncEnumerable 方法中的正确处置?

c# - WCF reference.cs 突然不包括类

asp.net-mvc - 在 ASP.NET MVC 项目 : compile OK, 中重命名命名空间运行不正常