Timespan Custom Model Binder

487 views Asked by At

I have a string type of a Time(ex: 5:00 PM) from a razor and I want to bind it to timespan when passing it to the controller.

Sample Code:

Razor:

@model Project.Models.MyModel

@Html.TextBoxFor(m => m.Time, new { @class = "sTime" , @id = "txtTime" })


<script type="text/javascript">
    $(function () {   
        $(".sTime").kendoTimePicker({
            format: "h:mm tt",
            parseFormats: ["HH:mm"]
        });
        $("#txtTime").data("kendoTimePicker").value("@Model.Time");
    });
 </script>

Controller:

[HttpPost]
public ActionResult Edit(MyModel model)
{
    //some code here.
    return View();
}

Model:

 public class MyModel
 {
     public TimeSpan Time { get; set; }
 }

Now, the problem is that the time cannot be bind from razor to the controller. The post value is always {00:00:00}.

How to achieve that using custom Model Binder?

1

There are 1 answers

3
Kiran Joshi On

You can use textboxfor() or hiddenfor() it pass the value to your controller

@{ 
    var modelList = (List<MyModel>)ViewBag.List;                                      
} 

@foreach (var item in modelList) {
    @Html.TextBox("time", item.Time.HasValue ? item.Time.Value.ToString() : 
    "", new { @class = "sTime" })
   @Html.HiddenFor(m=>m.Time) //just add this line with your model value.
}

<script type="text/javascript">
    $(function () {   
        $(".sTime").kendoTimePicker({
            format: "h:mm tt",
            parseFormats: ["HH:mm"]
        });
    });
 </script>