कस्टम मॉडल बांधने की मशीन लेखन यहाँ एक अच्छा विचार की तरह लगता है:
public class TimeSpanModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".TotalMinutes");
int totalMinutes;
if (value != null && int.TryParse(value.AttemptedValue, out totalMinutes))
{
return TimeSpan.FromMinutes(totalMinutes);
}
return base.BindModel(controllerContext, bindingContext);
}
}
और Application_Start
में पंजीकृत:
:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
ModelBinders.Binders.Add(typeof(TimeSpan), new TimeSpanModelBinder());
}
और अंत में हमेशा अपने ध्यान में रखते हुए दृढ़ता से टाइप किया सहायकों पसंद करते हैं
<% using (Html.BeginForm()) { %>
<%= Html.EditorFor(x => x.Interval) %>
<input type="submit" value="OK" />
<% } %>
और संबंधित संपादक टेम्पलेट (~/Views/Home/EditorTemplates/TimeSpan.ascx
):
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<TimeSpan>" %>
<%= Html.EditorFor(x => x.TotalMinutes) %>
अब आप अपने नियंत्रक के रूप में सरल हो सकता है:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Interval = TimeSpan.FromDays(1)
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// The model will be properly bound here
return View(model);
}
}
स्रोत
2010-11-02 16:10:48
निर्माण पूरी तरह से। इसने क्लिक नहीं किया कि उस तरह के मूल्य प्रदाता का उपयोग करके 'टाइमस्पेन' की संपत्ति से जुड़ना संभव होगा। धन्यवाद। –