在ASP.NET MVC中的dateTime对象 [英] dateTime object in ASP.NET MVC

查看:128
本文介绍了在ASP.NET MVC中的dateTime对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人成功地使用MVC中的模型绑定将2个文本框绑定到一个DateTime属性,我尝试了Scott的方法 http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx ,但不满意,因为这会阻止具有相同名称的HTML字段和模型属性(因此,如果验证无法设置正确的css,则失败)



我目前的尝试通过从bindingcontext中移除ValueProviderResult对象并为从日期结果和tiem组成的密钥添加一个新的(使用在Scotts post中的.Time约定),但是我有点担心会使用bindingContext对象直接混淆。



这个想法是我可以使用IDateErrorInfo和VAB PropertyComparisonValidator比较模型上的两个datetimes需要比另一个更晚,为了做到这一点,需要包括时间元素。

解决方案

我使用不同的方法去两种不同的模型集合:我的视图模型将有两个属性和这些字段的验证,而我的域模型将有一个DateTime。然后绑定后,我让视图模型更新域:

  public ActionResult Update(DateInput date)
{
if(date.IsValid)
{
var domain = someRepository.GetDomainObject(); //不完全,但你得到的想法。
date.Update(domain);
}
// ...
}

public class DateInput
{
public string Date {get;组; }
public string Time {get;组; }

public void Update(DomainObject domain){...}
}

public class DomainObject
{
public DateTime SomePointInTime {得到;组; }
}


Has anyone successfully bound 2 textboxes to one DateTime property using the model binding in MVC, I tried Scott's method http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx but was dissatisfied as this stops the HTML fields and Model properties having the same name (so the validation could not set the correct css if it failed).

My current attempt modifies this by removing the ValueProviderResult object from the bindingcontext and the adding a new one for the key made up from the date result and a tiem (using the .Time convention in Scotts post) but I am a little wary of messing around with the bindingContext object direct.

The idea is that i can use IDateErrorInfo and VAB PropertyComparisonValidator to compare 2 datetimes on the model where one needs to be later than the other, to do this the time element needs to be included.

解决方案

I use a different approach and go for two different sets of models: My view model would have two properties and the validation for those fields, while my domain model would have one DateTime. Then after the binding, I let the view model update the domain:

public ActionResult Update(DateInput date)
{
    if(date.IsValid)
    {
        var domain = someRepository.GetDomainObject(); // not exactly, but you get the idea.
        date.Update(domain);
    }
    // ...
}

public class DateInput
{
    public string Date { get; set; }
    public string Time { get; set; }

    public void Update(DomainObject domain) { ... }
}

public class DomainObject
{
    public DateTime SomePointInTime { get; set; }
}

这篇关于在ASP.NET MVC中的dateTime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆