Asp.net mvc UrlHelper.Action()跳过空属性
以下模型以两种方式使用:Asp.net mvc UrlHelper.Action()跳过空属性,asp.net-mvc,urlhelper,Asp.net Mvc,Urlhelper,以下模型以两种方式使用: public class SimpleModel { public DateTime? Date { get; set; } // Some other properties public SimpleModel() { Date = DateTime.Now; } } 在表单中使用模型时,生成的URL具有空参数日期(/Controller/Action?Date=&SomeOtherParams=123)
public class SimpleModel
{
public DateTime? Date { get; set; }
// Some other properties
public SimpleModel()
{
Date = DateTime.Now;
}
}
在表单中使用模型时,生成的URL具有空参数日期(/Controller/Action?Date=&SomeOtherParams=123
),并且模型中的Date
属性为null
(提交日期为空的表单后)
此模型还用作UrlHelper.Action()
中的第三个参数:
在这种情况下,如果Date
为空,则生成的URL不包含参数Date(/Controller/Action?SomeOtherParams=123
)。如果我遵循这个URL,则属性Date
是DateTime.Now
,并不像预期的那样为空
如何强制将空属性传递到URL
UPD。操作代码
public ActionResult MyAction( SimpleModel model = null )
{
if ( model.Date == null )
{
// show all
}
else
{
// show by date
}
}
实际上,使用了DropDownListFor
而不是TextBoxFor
@Html.DropDownListFor( model => model.Date, Model.Dates)
如果用户想查看所有实体,可以从下拉列表中选择日期,也可以将其保留为空
如果用户提交的表单日期为空,他将遵循URL/Controller/Action?Date=
,并获取所有实体(Date属性在构造函数中用默认值初始化,然后用null覆盖)
如果用户从其他页面(不提交表单)通过@url.Action
跟踪生成的url,则他只获得今天的实体,因为url不包含日期参数(/Controller/Action
)。在本例中,Date属性在构造函数中初始化,仅此而已
问题是
MyAction
中的model
从不等于null,我无法识别用户何时选择空日期以及何时只访问没有参数的页面。如果希望Date
为null,请删除分配DateTime的行。现在在空构造函数中
public SimpleModel()
{
//This line is assigning the value to Date whenever a new SimpleModel() is created. Comment it out.
// Date = DateTime.Now;
}
如果我遵循这个URL,属性Date是DateTime。现在,如预期的那样,不是null
问题是MVC引擎正试图基于您定义的构造函数构造一个Model
对象,该构造函数将Date
属性设置为DateTime.Now
。建议不要使用空参数定义构造函数,因为MVC引擎将使用它在POST
上创建模型。目前,这是预期的行为
如果需要该功能,请定义另一个构造函数:
public SimpleModel() // Left for MVC
{
}
public SimpleModel(DateTime date) // Use as: new SimpleModel(DateTime.Now) in your action
{
Date = date;
}
我不能这样做,它将改变
SimpleModel
行为。在处理url的操作方法中上载代码:/Controller/action?SomeOtherParams=123
我在帖子中解释了我需要什么。参见UPD。我发现了非常肮脏的解决方案:@Url.Action(“Action”,“Controller”,Model)&;Date=
将生成/Controller/Action?SomeOtherParams=123&Date=
我描述不正确,是的,这是预期的行为。我使用这个预期的行为在构造函数中用默认值设置Date
。问题是我无法识别用户何时选择空日期以及何时只访问没有参数的页面(在这种情况下,Date
必须有默认值,而不是null)。所以,您希望Date
为null
,这样您就可以检查是否选择了,对吗?在这种情况下,这将永远不会发生,因为您总是将Date
设置为DateTime。现在在构造函数中设置。现在,问题是通过Url.Action
方法传递模型
,解析模型后会遇到问题。最好将日期本身传递给操作
。
public SimpleModel()
{
//This line is assigning the value to Date whenever a new SimpleModel() is created. Comment it out.
// Date = DateTime.Now;
}
public SimpleModel() // Left for MVC
{
}
public SimpleModel(DateTime date) // Use as: new SimpleModel(DateTime.Now) in your action
{
Date = date;
}