The model below used in two ways:
public class SimpleModel
{
public DateTime? Date { get; set; }
// Some other properties
public SimpleModel()
{
Date = DateTime.Now;
}
}
When model is used in the form, generated URL have empty parameter Date (/Controller/Action?Date=&SomeOtherParams=123
) and Date
property in model is null
(after submitting form with empty date).
...
@Html.TextBoxFor(model => model.Date)
...
Also this model used as third parameter in UrlHelper.Action()
:
@Url.Action("Action", "Controller", Model) // Model is SimpleModel
In this case if Date
is null, generated URL does not contains parameter Date (/Controller/Action?SomeOtherParams=123
). And if I following this URL, property Date
is DateTime.Now
, not null as expected.
How to force passing empty properties to URL?
UPD. Action code
public ActionResult MyAction( SimpleModel model = null )
{
if ( model.Date == null )
{
// show all
}
else
{
// show by date
}
}
Actually, instead of TextBoxFor
used DropDownListFor
.
@Html.DropDownListFor( model => model.Date, Model.Dates)
User can choose Date from DropDown or live it empty if he want to see all entities.
If user submiting form with empty Date, he following URL /Controller/Action?Date=
and getting all entities (Date property was initialized with default value in constructor and then overriten with null).
If user following by generated url via @Url.Action
from other page (not submitting form), he getting only todays entities, because URL not contains Date parameter (/Controller/Action
). In this case Date property initializing in constructor and this is all.
Problem is model
in MyAction
never equals null and I cant recognize when user selects empty Date and when he just visit page without parameters.