user3793029
user3793029

Reputation: 135

How to pass selected date as input in MVC4?

when i used the below code, i am getting null reference not set to an instance of an object in mvc4. I used FormCollection method to pass date as input. It shows me null value for sd (sd is startdate variable) while i traced out. How to resolve this exception?

Controller:

    [HttpPost]

    public ActionResult Index(FormCollection formCollection)
    {
        List<tblGroup> allg = new List<tblGroup>();

        using (portalconnectionstring con = new portalconnectionstring())
        {
            allg = con.grt.OrderBy(m => m.groupname).ToList();

        }
        ViewBag.disg = new SelectList(allg, "groupid", "groupname");
        var sd = formCollection["txtDate"];  //Showing null value here while i traced out
        var ed = formCollection["Txtenddate"];

          ....
         .....
     }

View:

@using (Html.BeginForm("Index","MyController",FormMethod.Post,new {id="form1"}))

{
               <div>

                @Html.Label(" ",new { id ="Label1" })
               <input id="txtDate" type="text" value="Startdate: "/>
                <div> 
                <input id="Txtenddate" type="text" value="Enddate: "/> 
              </div>
               <div> 
                @Html.Label("Group Name", new{id="lblGroupName"}) 
                 </div>
            <div> 
  @Html.DropDownListFor(model => model.groupid, @ViewBag.disg as SelectList, "select") 
                                       @Html.ValidationMessageFor(model=>model.groupid)
           </div>
               <input type="submit" id="Button1" Value="Submit"/>
                            </div>

    }

Upvotes: 0

Views: 517

Answers (1)

user3559349
user3559349

Reputation:

You need to give your inputs a name attribute

<input id="txtDate" name="txtDate" type="text" value="Startdate: "/>

However this will be done automatically if you use the html helpers to bind to your model properties, for example @Html.TextBoxFor(m => m.txtDate), in which case you can bind back to you model in the POSt method rather than using FormCollection

Upvotes: 2

Related Questions