2017-01-15 19 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"/> 
} 

私のカスタムモデルバインダーを使用すると空の結果が得られます。どうして?私のモデルバインダーは単純であり、それは特別な何もしません。

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

私はglobal.asaxにこのモデルバインダーを登録した後、私はTextBoxForに空の文字列を取得します。何かお考えですか?

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

そして、私のモデル:

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

私は私がする必要がある理由がわからない:

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

答えて

1

私はちょうど私のカスタムモデルバインダーに次の行を追加することにより、私の問題を解決しましたこの行を追加せずにデータ型が文字列のときに動作しているためこの行を追加しますが、この行を追加しないとDateTime型では動作しません。私は本当に誰かがそれを私に説明することを願っています。