2017-01-15 38 views
0

當我有一個ActionLink這樣的:怪異結果使用型號粘合劑

@Html.ActionLink("Click", "Create", "Default1", new {date = Model.Date} , null) 

這是Create

public ActionResult Create(DateTime? date) 
{ 
    return View(); 
} 

這是完全示出在創建視圖:

@using (Html.BeginForm()) 
{ 
    @Html.TextBoxFor(m => m.Date) //I get the correct value here 
    <input type="submit" value="Save"/> 
} 

但是,當我使用我的自定義模型活頁夾時,我得到空的結果。爲什麼?我的模型綁定很簡單,並沒有做什麼特別的:我登記我global.asax我得到的TextBoxFor空字符串這個模型綁定後

public class SimpleModelBinder : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
     return DateTime.Parse(valueResult.AttemptedValue); 
    } 
} 

。你有什麼想法嗎?

ModelBinders.Binders.Add(typeof(DateTime?), new SimpleModelBinder()); 

而且我的模型:

public class Test 
{ 
    public int Id { get; set; } 
    public DateTime? Date { get; set; } 
} 

回答

1

我只是解決了我的問題,通過添加以下行到我的自定義模型綁定:

bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueResult); 

我不知道爲什麼我需要添加此行是因爲它在數據類型爲字符串時正在工作而不添加此行,但未添加此行,它不適用於DateTime類型。我真的希望有人向我解釋。