加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 内部模型的自定义模型绑定器

发布时间:2020-12-16 03:58:16 所属栏目:asp.Net 来源:网络整理
导读:我有一个这样的模型: public class MainModel{ public string Id {get;set;} public string Title {get;set;} public TimePicker TimePickerField {get;set;}} TimePicker是一个内部模型,如下所示: public class TimePicker { public TimeSpan {get;set;}
我有一个这样的模型:

public class MainModel
{
   public string Id {get;set;}
   public string Title {get;set;}
   public TimePicker TimePickerField {get;set;}
}

TimePicker是一个内部模型,如下所示:

public class TimePicker 
{
   public TimeSpan {get;set;}
   public AmPmEnum AmPm {get;set;}
}

我正在尝试为内部模型创建自定义模型绑定:TimePicker

问题是:如何获取以表格形式提交到TimePicker模型字段的自定义模型绑定器中的值?

如果我试着像这样:

var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

我只是价值无效.

我不确定如何正确实现模型绑定器.

public class TimePickerModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException("bindingContext");
        }
        var result = new TimePicker();

        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (value != null)
        {
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName,value);
            try
            {
                //result = Duration.Parse(value.AttemptedValue);
            }
            catch (Exception ex)
            {
               bindingContext.ModelState.AddModelError(bindingContext.ModelName,ex.Message);
            }
        }    

        return result;
    }
}

解决方法

以下适用于我.

模型:

public enum AmPmEnum
{
    Am,Pm
}

public class TimePicker 
{
    public TimeSpan Time { get; set; }
    public AmPmEnum AmPm { get; set; }
}

public class MainModel
{
    public TimePicker TimePickerField { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MainModel
        {
            TimePickerField = new TimePicker
            {
                Time = TimeSpan.FromHours(1),AmPm = AmPmEnum.Pm
            }
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MainModel model)
    {
        return View(model);
    }
}

查看(?/ Views / Home / Index.cshtml):

@model MainModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.TimePickerField)
    <button type="submit">OK</button>
}

自定义编辑器模板(?/ Views / Shared / EditorTemplates / TimePicker.cshtml),它将Time和AmPm属性合并到一个输入字段中,以后需要自定义模型绑定器才能在提交表单时拆分它们:

@model TimePicker
@Html.TextBox("_picker_",string.Format("{0} {1}",Model.Time,Model.AmPm))

和模型绑定器:

public class TimePickerModelBinder : IModelBinder
{
    public object BindModel(
        ControllerContext controllerContext,ModelBindingContext bindingContext
    )
    {
        var key = bindingContext.ModelName + "._picker_";
        var value = bindingContext.ValueProvider.GetValue(key);
        if (value == null)
        {
            return null;
        }

        var result = new TimePicker();

        try
        {
            // TODO: instead of hardcoding do your parsing
            // from value.AttemptedValue which will contain the string
            // that was entered by the user
            return new TimePicker
            {
                Time = TimeSpan.FromHours(2),AmPm = AmPmEnum.Pm
            };
        }
        catch (Exception ex)
        {
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName,ex.Message
            );
            // This is important in order to preserve the original user
            // input in case of error when redisplaying the view
            bindingContext.ModelState.SetModelValue(key,value);
        }
        return result;
    }
}

最后在Application_Start中注册模型绑定器:

ModelBinders.Binders.Add(typeof(TimePicker),new TimePickerModelBinder());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读