我尝试为日期输入制作3个下拉列表。提交后,BindModel
中的IModelBinder
方法将日,月和年组合为一种类型。我的问题是缺少数据,控制器收到一个新的“测试日”
public class DateAndTimeModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var request = controllerContext.HttpContext.Request;
int day, month, year;
day = int.Parse(bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".day").AttemptedValue);
month = int.Parse(bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".month").AttemptedValue);
year = int.Parse(bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".year").AttemptedValue);
DateTime date = new DateTime(year, month, day);
TestDay tday = new TestDay();
tday.Day2T = date;
return tday;
}
}
控制器:
[HttpPost]
//[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID, Day2T.day, Day2T.day.month")]TestDay testday)
{
if (ModelState.IsValid)
{
db.TestDays.Add(testday);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(testday);
}
Html代码:
<div class="col-md-10">
@Html.DropDownListFor(model => model.Day2T.Day, Enumerable.Range(1, 31).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }), "Day")
@Html.ValidationMessageFor(model => model.Day2T.Day)
@Html.DropDownListFor(model => model.Day2T.Month, Enumerable.Range(1, 12).Select(i => new SelectListItem { Value = i.ToString(), Text = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i) }), "Month")
@Html.ValidationMessageFor(model => model.Day2T.Month)
@Html.DropDownListFor(model => model.Day2T.Year, Enumerable.Range(1900, 117).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }), "Year")
@Html.ValidationMessageFor(model => model.Day2T.Year)@**@
</div>
答案 0 :(得分:0)
此问题已修复。我想要新手的帖子可以找到答案,如果他们有同样的问题。 我忘了在Global.asax.cs
中发布代码ModelBinders.Binders.Add(typeof(DateTime),new DateAndTimeModelBinder());
我在控制器中删除[Bind(包括=&#34; ID,Day2T.day,Day2T.day.month&#34;)]。
public ActionResult Edit([Bind(Include="ID,Day2T")] TestDay testday)
并在BindModel函数中更改return:
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
...
DateTime date = new DateTime(year, month, day);
...
return date;
}