Model Binder-
I have a customer model like -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ModelBinder.Models
{
public class Customer
{
public string CustomerName { get; set; }
public string CustomerCode { get; set; }
}
}
Now, i am creating view on based on Customer model,ie, also known as Strongly typed view.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ModelBinder.Models.Customer>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>CustomerDatsils</title>
</head>
<body>
<div>
<%= Html.LabelFor(model => model.CustomerCode)%> :
<%= Html.TextBoxFor(model => model.CustomerCode) %> <br />
<%= Html.LabelFor(model => model.CustomerName)%> :
<%= Html.TextBoxFor(model => model.CustomerName) %>
</div>
</body>
</html>
So, when we post the data on server side to manupulate operations lke
[HttpPost]
public ActionResult CustomerDatsils(Customer customer)
{
return View("CustomerDatsils", customer);
}
So, we get the all model properties values filled automatically known as Default model binder. Its values filled automatically due to model properties name same as the controls name.
Suppose, i have changed the controls names or can say not creating strongly typed view like as
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>CustomerInfo</title>
</head>
<body>
<div>
<form action="Home/CustomerDatsils" method="post">
Customer Code : <input id="txtCustomerCode" name="txtCustomerCode" type="text" /><br />
Customer Name : <input id="txtCustomerName" name="txtCustomerName" type="text" /><br />
<input id="Submit1" type="submit" value="submit" />
</form>
</div>
</body>
</html>
So, in this senario when i post the data on server side then gets model properties values null. because model properties names is not same as controls names in view. So, to bind model properties values with different controls names and get filled values of model when we post data on server, it can be possible by Custom model binder.
public class CustomerBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpContextBase context = controllerContext.HttpContext;
string custCode = context.Request.Form["txtCustomerCode"];
string custName = context.Request.Form["txtCustomerName"];
Customer cust = new Customer()
{
CustomerCode =custCode,
CustomerName =custName
};
return cust;
}
}
[HttpPost]
public ActionResult CustomerDatsils(
[ModelBinder(typeof(CustomerBinder))]
Customer info)
{
return View("CustomerDatsils", info);
}
No comments:
Post a Comment