Question

I'm working on a school project and I need some help. I've created a form and I want to get the submitted values from it. Is it possible to do this without using JavaScript? And in that case, how do I do it?

Form:

<div id="secondRowInputBox">
        <% using (Html.BeginForm("Index","Home",FormMethod.Post))
        {%>
            <%= Html.TextBox("Id")%> <br />
            <%= Html.TextBox("CustomerCode") %><br />
            <%= Html.TextBox("Amount") %><br />
            <input type="submit" value="Submit customer data" />
        <%} %>
    </div>
Was it helpful?

Solution 2

You have already done half the work, now in home controller make an actionresult

[HttpPost]
public ActionResult Index(int id, string customerCode, int amount)
{
// work here.
}

form post method will call this method, as you have specified it in the begin form parameters.

It will be better if you use a model for passing values and use it in view for form elements

[HttpPost]
public ActionResult Index(ModelName modelinstance)
{
// work here.
}

Sample loginModel

public class LoginModel
{
    [Required]
    [Display(Name = "Username:")]
    public String UserName { get; set; }

    [Required]
    [Display(Name = "Password:")]
    [DataType(DataType.Password)]
    public String Password { get; set; }
}

now if was using this login model in the form

then for the controller action, modelinstance is simply the object of model class

[HttpPost]
public ActionResult Index(LoginModel loginDetails)
{
// work here.
}

if you have a lot of variables in the form then having a model helps as you don't need to write for all the properties.

OTHER TIPS

Just create an HttpPost action in your controller accepting the form values as parameters:

[HttpPost]
public ActionResult Index(int id, string customerCode, int amount)
{
    // You can change the type of the parameters according to the input in the form.
    // Process data.    
}

You might want to look into model binding. This allows you to create strongly-typed views and saves you the trouble of creating actions with dozens of parameters.

Henk Mollema's answer is good. Here to say something more on it.

Html.TextBox will generate html like below one, there's a name attribute.

<input id="CustomerCode" name="CustomerCode" type="text">

When you submit the form, all the values of input fields can be get from Request.Form by name attribute as key Request.Form["CustomerCode"], and ASP.NET MVC has done some magic for us, so it can simply go into the param of the action method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top