ModelBinder سفارشی در ASP.NET MVC
نویسنده: ناصر طاهری
تاریخ: ۱۳۹۲/۰۴/۲۰ ۸:۲۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public class CustomerInfo
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
}public interface IModelBinder
{
object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext);
}using System;
using System.Web;
using System.Web.Mvc;
using ModelBinderExample.Models;
using Persia;
namespace ModelBinderExample.CustomModelBinder
{
// Article written for www.dotnettips.info
public class CustomerInfoModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;
string firstName = request.Form.Get("FirstName");
string lastName = request.Form.Get("LastName");
DateTime birthDate = this.GetMiladiDate(request);
return new CustomerInfo()
{
FirstName = firstName,
LastName = lastName,
BirthDate = birthDate
};
}
private DateTime GetMiladiDate(HttpRequestBase request)
{
int day = int.Parse(request.Form.Get("Day"));
int month = int.Parse(request.Form.Get("Month"));
int years = int.Parse(request.Form.Get("Years"));
//Convert shamsi to miladi
return Persia.Calendar.ConvertToGregorian(years, month, day, DateType.Gerigorian);
}
}
}protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
//Register New ModelBinder
ModelBinders.Binders.Add(typeof(CustomerInfo), new CustomerInfoModelBinder());
}[HttpPost]
public ActionResult Create([ModelBinder(typeof (CustomerInfoModelBinder))] CustomerInfo customerInfo)
{
if (ModelState.IsValid)
{
ViewBag.FirstName = customerInfo.FirstName;
ViewBag.LastName = customerInfo.LastName;
ViewBag.BirthDate = customerInfo.BirthDate;
}
return View();
}public ActionResult Create(CustomerInfo customerInfo)
ModelBinders.Binders.Add(typeof(CustomerInfo), new CustomerInfoModelBinder());
public class Model
{
public Model()
{
Items = new List<ItemModel>();
}
public Guid Id { get; set; }
public Guid ProductId { get; set; }
public List<ItemModel> Items { get; set; }
}
public class ItemModel
{
Public Guid Id
public string Title{ get; set; }
public int Value { get; set; }
} @model List<Model>