C#表单仍然没有必填字段

时间:2018-05-07 20:24:35

标签: c# asp.net-mvc viewmodel

我正在尝试创建一个View字段,但由于某种原因,它不起作用(我可以点击提交,它的POST是表单)而不必强制选择一个值。我错过了什么?

查看(CardCreate.cshtml)

@model xxx.Models.TicketsViewModels.CardCreateViewModel

<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>

<div>
    @Html.LabelFor(m => m.Title)
    @Html.TextBoxFor(m => m.Title)
    @Html.ValidationMessageFor(m => m.Title)
</div>

ViewModel(CardCreateViewModel.cs)

[Required(ErrorMessage = "Title is required")]
[Display(Name = "Title")]
public string Title { get; set; }

Controller(TicketsController.cs)

[HttpPost]
public async Task<ActionResult> CardCreate(CardCreateViewModel c)
{
    if (!this.ModelState.IsValid)
    {
        return View("CardCreate", c);
    }
    //adding other data

}

1 个答案:

答案 0 :(得分:0)

ASP.NET MVC的验证不是客户端,而是服务器端。什么都不会阻止浏览器提交它。您的控制器操作需要将HTML视图返回到浏览器并显示验证消息:

[HttpGet]
public ActionResult Index()
{
    return this.View( new IndexViewModel() );
}

[HttpPost]
public ActionResult Index( IndexViewModel model )
{
    // Immediately prior to execution entering this `Index` action method, the ASP.NET MVC runtime will populate the `Controller.ModelState` object with information about validation errors in `model`.

    if( !this.ModelState.IsValid )
    { 
        // When the View is rendered the `ValidationMessageFor` helper will inspect the ModelState and show the error message itself, so no custom logic is needed here
        return this.View( model );
    }

    // TODO: Do processing of valid data here

    // Upon successful processing/saving/etc, redirect back to the GET view:
    return this.RedirectToAction( nameof(this.Index) );
}

ASP.NET MVC确实附带了一些用于客户端验证的脚本,但它是可选的,并不像ASP.NET WebForms中的验证控件那样是平台的组成部分。但是,客户端验证仅为了方便访问者:它不会添加任何实际的安全性,禁用JavaScript的访问者将看不到客户端验证消息。 Never trust the client