ASP.NET MVC C# : HiddenFor to controller

I have the following markup and code.

View:

@model WealthRef.Models.ViewModels

<td style="width: 100px;color:black" id="tdfromDatevalue">
if (Model != null)
{
    @Html.DropDownListFor(model => Model.DropDownModels.FromDateModels.SelectedNode,
        new SelectList(Model.DropDownModels.FromDateModels.FromDateValues, 
                       "Code", "CodeDescription"),
        new { id = "ddlFromDateValues", 
              @class = "chosen-select",
              data_placeholder = "Select Date...", 
              style = "white-space:nowrap;width:100px;" })
    @Html.HiddenFor(model => Model.FromDate, new { id = "hdnFromDate" })
}
</td>

<script type="text/javascript" language="javascript">
$("#ddlFromDateValues").on("change", function () {
    var fromDate = $(this).val();
    $("#ddlFromDateValues").val(fromDate).trigger("chosen:updated");
    $("#hdnFromDate").val(fromDate);
});
</script>
<td>
    <a class="btn" href="@Url.Action("ExportToExcel", "WealthRef")" id="btnRun"
       style="color:White" onclick="return Validate();">Run</a>
</td>
<script>
$(document).ready(function () {
    load();
});

function load() {
    $("#hdnFromDate").val($("#ddlFromDateValues").find("option:selected").val());
}
</script>

Model:

namespace WealthRef.Models
{
    public class ViewModels
    {
        public string FromDate { get; set; }
    }
}

Controller:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult ExportToExcel(ViewModels model)
{
    string FromDate = model.FromDate;
}

I expected to get the FromDate from the hidden field, which is from the selected item from the @Html.DropDownListFor, but I got null.

Please help!

Thanks!

  • model =\> <– This is not valid C# Razor.

    – 

  • Your <script> elements are really messed-up… you probably should rectify that first.

    – 

Leave a Comment