User User - 1 year ago 62
ASP.NET (C#) Question

How to get textbox value from view to controller in mvc4 on submit button click

How to get the textbox value from view to controller in mvc4?If I using httppost method in controller the page cannot found error was came.


@model MVC_2.Models.FormModel

ViewBag.Title = "DisplayForm";

@using (Html.BeginForm("DisplayForm", "FormController", FormMethod.Post))
@Html.LabelFor(model => model.Empname)
@Html.TextBoxFor(model => model.Empname)
@* @Html.Hidden("Emplname", Model.Empname)*@

@Html.LabelFor(model => model.EmpId)
@Html.TextBoxFor(model => model.EmpId)
@* @Html.Hidden("Emplid", Model.EmpId)*@

@Html.LabelFor(model => model.EmpDepartment)
@Html.TextBoxFor(model => model.EmpDepartment)
@* @Html.Hidden("Empldepart", Model.EmpDepartment)*@

<input type="button" id="submitId" value="submit" />



public class FormModel
public string _EmpName;
public string _EmpId;
public string _EmpDepartment;

public string Empname
get {return _EmpName; }
set { _EmpName = value; }

public string EmpId
get { return _EmpId;}
set {_EmpId =value;}

public string EmpDepartment
get { return _EmpDepartment; }
set { _EmpDepartment = value; }


public ActionResult DisplayForm()
FormModel frmmdl = new FormModel();
frmmdl.Empname=**How to get the textbox value here from view on submitbutton click???**

Answer Source

First you need to change your button type to "submit". so your form values will be submitted to your Action method.


<input type="button" id="submitId" value="submit" />


<input type="submit" id="submitId" value="submit" />

Second you need to add your model as parameter in your Action method.

public ActionResult DisplayForm(FormModel model)
       var strname=model.Empname;
             return View();

Third, If your Controller name is "FormController". you need to change the parameter of your Html.Beginform in your view to this:

@using (Html.BeginForm("DisplayForm", "Form", FormMethod.Post))

    //your fields

P.S. If your view is the same name as your Action method which is "DisplayForm" you don't need to add any parameter in the Html.BeginForm. just to make it simple. like so:

@using (Html.BeginForm())
//your fields
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download