2

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>

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

How do I use the modelinstance to get the values?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.