mercredi 11 octobre 2017

why Data Annotation with model-binder in asp.net MVC5 not working?

i can't understand why model binder not validate data. My code is working fine without model binder. The action i tried to invoke is Enter. So, the url is like this. (localhost:51017/Customer/Enter). My code is given below.

Customer Controller.cs

public class CustomerController : Controller
{
    // GET: Customer
    public ActionResult Load()
    {
        Customer obj = new Customer()
        {
            CustomerCode = "1001",
            CustomerName = "Rezwan"
        };
        return View("Customer", obj);
    }
    public ActionResult Enter()
    {
        return View("EnterCustomer");
    }

    public ActionResult Submit([ModelBinder(typeof(CustomerBinder))] Customer obj)
    {
        if (ModelState.IsValid)
            return View("Customer", obj);
        else
            return View("EnterCustomer");      
    }
}

EnterCustomer.cshtml

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>EnterCustomer</title>
</head>
<body>
    <div> 
        <form action="Submit" method="post">
            Customer Name - <input name="txtCustomerName" type="text" />
            Customer Code - <input name="txtCustomerCode" type="text" />
            <input id="Button1" type="submit" value="submit" />
         </form>
        @Html.ValidationSummary()
    </div>
</body>
</html>

Customer.cs

 public class Customer
{
    [Required]
    [RegularExpression("^[A-Z]{3,3}[0-9]{4,4}$")]
    public string  CustomerCode { get; set; }

    [Required]
    [StringLength(10)]
    public string CustomerName { get; set; }
}

CustomerBinder.cs

 public class CustomerBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        HttpContextBase objContext = controllerContext.HttpContext;
        string CustCode = objContext.Request.Form["txtCustomerCode"];
        string CustName = objContext.Request.Form["txtCustomerName"];

        Customer obj = new Customer()
        {
            CustomerCode = CustCode,
            CustomerName = CustName
        };

        return obj;

    }
}

Customer.cshtml

@model HelloWorld.Models.Customer

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Customer</title>
</head>
<body>
    <div> 
        Name - @Model.CustomerName <br/>
        Code - @Model.CustomerCode
    </div>
</body>
</html>

Please help me out. I'm new in asp.net language.

Aucun commentaire:

Enregistrer un commentaire