为什么我的必填信息在提交前显示?

时间:2014-08-05 08:09:40

标签: asp.net-mvc

我有这个控制器用于创建新的客户类型。如果用户创建相同的客户两次,代码可以工作,它会创建新客户,发送错误。

但问题是,在开始时(当用户来形成时)它已经警告我的字段是必需的!我想在提交后显示必需(如果输入字段为空)。

我的模特是:

public class CustomerType
{
    public int IdNewType { get; set; }

    [Required(ErrorMessage = "Customer is required!")]
    public string CustomType { get; set; }

}

控制器是:

public ActionResult CreateNewCustomerType(Models.CustomerType customerType)
{
try
{
  using (var dataC = new userDbEntities())
  {
     var sysCustomerType = dataC.CustomTypes.Create();

     if (sysCustomerType != null)
     {
        sysCustomerType.CustomerType = customerType.CustomType;

        var count = dataC.CustomTypes.Count(c => c.CustomerType == customerType.CustomType);
        if (count == 0)
        {
           dataC.CustomTypes.Add(sysCustomerType);
           dataC.SaveChanges();
           return RedirectToAction("CustomerTypeView", "LoginAdmin");
         }
         else
         {
            ModelState.AddModelError("CustomType", "This customer alerady exists!");
         }
      }
      else
      {
         ModelState.AddModelError("CustomType", "");
      }
   }
}
catch (Exception ex)
{
   string error = ex.Message;
}
return View(customerType);
}  

在View中,我使用它来显示错误:

@model AdminRole.Models.CustomerType
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()  
    <label class="control-label" for="us">Stranka</label>
        @Html.HiddenFor(model => model.IdNewType)
        @Html.TextBoxFor(u => u.CustomType, new{@class="form-control", id="us"})

    <span>@Html.ValidationSummary(false, null, new{@class="alert alert-danger alert-dismissible", role="alert"})</span>

        <input class="btn btn-default pull-left btn-success" type="submit" value="Create"/>

}

感谢您的帮助......

1 个答案:

答案 0 :(得分:2)

public ActionResult CreateNewCustomerType()
{
    return view();
}

[HttpPost]
public ActionResult CreateNewCustomerType(Models.CustomerType customerType)
{
    /* ... */
}

试试这样。我认为这将解决您的问题。