簡體   English   中英

使用模型活頁夾時很奇怪的結果

[英]Weird result when using Model binder

我有一個像這樣的ActionLink

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

這是Create

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

這在create視圖中完美顯示:

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

但是,當我使用自定義的Model Binder時,會得到空的結果。 為什么? 我的模型活頁夾很簡單,沒有做任何特別的事情:

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());

而我的模型:

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

我只是通過將以下行添加到自定義Model Binder中來解決了我的問題:

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

我不知道為什么需要添加此行,因為當數據類型為字符串而不添加此行時它可以工作,但是如果不添加此行則它不能與DateTime類型一起工作。 我真的希望有人向我解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM