如何添加验证以显示用户名已经退出ASP .net MVC?

时间:2016-02-02 06:34:46

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

实际上我的要求是我应该验证用户是否是现有的供应商?如果用户名已存在,则应显示供应商名称或供应商代码已退出,因此请选择其他名称或代码。 (注意:这里我应该验证名称和代码) 这是我的代码

     public ActionResult CreateSupplier()
    {

        var suppliers = db.Suppliers;
        ViewBag.Suppliers = suppliers;
        return View();

    }

    [HttpPost]
    public ActionResult CreateSupplier(Supplier supplier)
    {

      try{

        if (ModelState.IsValid)
        {

            supplier.CreatedbyUserId = Convert.ToInt32(this.Session["_SessionUserId"]);
            supplier.UpdatedbyUserId = Convert.ToInt32(this.Session["_SessionupdatedUserId"]);
            supplier.CreatedDate = Convert.ToDateTime(this.Session["_SessionDate"]);
            db.Suppliers.Add(supplier);
            db.SaveChanges();
            return Redirect("CreateSupplier");  
        }
        }

    catch (Exception ex)
        {
           throw (ex);
        }
        else   
        {
            return View();
        }
    }

我在Global.asax页面中使用了这段代码

    protected void Session_Start(Object sender, EventArgs e)
    {
        int userId = 1;
        int updatedUserId = 1;
        HttpContext.Current.Session.Add("_SessionUserId", userId);

        HttpContext.Current.Session.Add("_SessionupdatedUserId", updatedUserId);

        DateTime createdDate = DateTime.Now;
        HttpContext.Current.Session.Add("_SessionDate", createdDate);

    }

我的cshtml代码是

        <div class=" col-lg-3 col-sm-2 col-md-2 col-xs-3">
                                    @Html.LabelFor(model => model.SupplierName, new { @class = " form-control-label", style = "font-size:15px" })
                                </div>
                                <div class=" col-lg-6 col-sm-10 col-md-10 col-xs-10">
                                    @Html.TextBoxFor(model => model.SupplierName, new { @class = "form-control display-inline", id = "Name" }) 
                                    @Html.ValidationMessageFor(a => a.SupplierName)
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="row">
                                <div class=" col-lg-3 col-sm-2 col-md-2 col-xs-3">
                                    @Html.LabelFor(model => model.SupplierCode, new { @class = " form-control-label", style = "font-size:15px" })
                                </div>
                                <div class=" col-lg-6 col-sm-10 col-md-10 col-xs-10">
                                    @Html.TextBoxFor(model => model.SupplierCode, new { @class = "form-control display-inline", id = "Name" })
                                    @Html.ValidationMessageFor(model => model.SupplierCode)
                                </div>
                            </div>
                        </div>

请帮助我如何解决它。

谢谢, Kirankuamr

2 个答案:

答案 0 :(得分:0)

 public ActionResult CreateSupplier()
{

    var suppliers = db.Suppliers;
    ViewBag.Suppliers = suppliers;
    return View();

}

[HttpPost]
public ActionResult CreateSupplier(Supplier supplier)
{

  try{

    if (ModelState.IsValid)
    {

        supplier.CreatedbyUserId = Convert.ToInt32(this.Session["_SessionUserId"]);
        supplier.UpdatedbyUserId = Convert.ToInt32(this.Session["_SessionupdatedUserId"]);
        supplier.CreatedDate = Convert.ToDateTime(this.Session["_SessionDate"]);
Suppliers objSup = new Suppliers();
 objSup = db.Suppliers.Where(x=>x.CreatedbyUserId ==supplier.CreatedbyUserId).FirstOrDefault();
if(objSup !=null){
        db.Suppliers.Add(supplier);
        db.SaveChanges();
        return Redirect("CreateSupplier");  
    }
else{
 ModelState.AddModelError("","Suplier already exists.");
    }
    }
    }

catch (Exception ex)
    {
       throw (ex);
    }
    else   
    {
        return View();
    }
}

cshtml代码是

@using(Html.BeginForm()){
 <div class=" col-lg-3 col-sm-2 col-md-2 col-xs-3">
                                @Html.LabelFor(model => model.SupplierName, new { @class = " form-control-label", style = "font-size:15px" })
                            </div>
                            <div class=" col-lg-6 col-sm-10 col-md-10 col-xs-10">
                                @Html.TextBoxFor(model => model.SupplierName, new { @class = "form-control display-inline", id = "Name" }) 
                                @Html.ValidationMessageFor(a => a.SupplierName)
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="row">
                            <div class=" col-lg-3 col-sm-2 col-md-2 col-xs-3">
                                @Html.LabelFor(model => model.SupplierCode, new { @class = " form-control-label", style = "font-size:15px" })
                            </div>
                            <div class=" col-lg-6 col-sm-10 col-md-10 col-xs-10">
                                @Html.TextBoxFor(model => model.SupplierCode, new { @class = "form-control display-inline", id = "Name" })
                                @Html.ValidationMessageFor(model => model.SupplierCode)
                            </div>
                        </div>
                    </div>
}

答案 1 :(得分:0)

您可以为此编写自定义验证器。

public class ValidateUserName: ValidationAttribute
{
    string userName;
    public ValidateUserName(string userName)
    {
        this.userName = userName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
    if (UserNameExist())
    {
        return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
    }
    return null;
    }
}

并检查SP中的用户名并根据UserNameExist()内的内容返回bool。并在模型属性

上使用此属性
[ValidateUserName]
public string UserName {get; set;}