POST/Submit/Save a Model with custom DataType

619 views Asked by At

I have created a custom DataType("Days") and have been able to create a partial view "Days.cshtml" which renders a select list just fine.

I am able to populate the select list from the form just fine, but I can't seem to find any documentation as to how to post the Model with the custom DataType values populated.

public class TimeRequestModel
{
    public int EmployeeID { get; set; }
    public int JobAllocationID { get; set; }
    [DataType("Days")]
    public List<SelectListItem> Days { get; set; }
}

Days.cshtml (the model will most likely be null as we are creating new "Days")

@model TimeRequestModel
@Html.DropDownList("", (Model != null ? Model.Days : new List<SelectListItem>()), new { @class = "customfield", @type = "custom", @multiple = "multiple", @size = "14", @style = "text-align: center; float: right; width: 225px;" })

My Controller:

[HttpPost]
    public ActionResult CreateRequest(TimeRequestModel timeRequest)
    {
        if (ModelState.IsValid)
        {
            translator.CreateTimeRequest(timeRequest);
            return RedirectToAction("Index");
        }

        return View(timeRequest);
    }

And upon POSTing the Model, timeRequest.Days is always null.

1

There are 1 answers

3
Dmitry Efimenko On

In your ViewModel add one more property: string DaysSelectedValue

Make your DropDownList to look like this:

@Html.DropDownList(model => model.DaysSelectedValue, Model.Days, new { @class = "customfield", @type = "custom", @multiple = "multiple", @size = "14", @style = "text-align: center; float: right; width: 225px;" })

I did not really understand why you are checking if the Model is null in the view. From what I'm seeing, it should never be null.