Thomas
Thomas

Reputation: 34188

Value is not getting pass from view to action method

i am new in mvc. i have design a form and when i am click the submit button then right action method is calling but form field's value are not getting pass.

here is my view code

<div id="mydiv">
@using (Html.BeginForm("Save", "Game", FormMethod.Post, new { @Id = "Form1" }))
{
    <table border="0">
    <tr>
        <td>Name :</td>
        <td><input name="name" type="text" /></td>
    </tr>

     <tr>
        <td>Salary :</td>
        <td><input name="salary" type="text" /></td>
    </tr>
    <tr>
        <td colspan="2"><input type="submit" value="Save" /> </td>
    </tr>
    </table>
}
</div>

here is my action method

 public ActionResult Save(string str1, string str2)
 {
     return View("Message");
 }

when save is getting called the str1 & str2 is being null please help me to pass value and also discuss various trick to pass value from view to action method. thanks

Upvotes: 0

Views: 2412

Answers (3)

Satpal
Satpal

Reputation: 133403

Change you controller

public ActionResult Save(string name, string salary)
{
    return View("Message");
}

As you have to use variable name which you have defined in input

<input name="name" type="text" />
<input name="salary" type="text" />

If you want to return partial view.

 return PartialView("Message", <<OptionalPartialViewModel>>);

Upvotes: 4

Fals
Fals

Reputation: 6839

MVC Bind form inputs to Action by their names. You should change your method params as the same of the form. Also, you are missing the HttpPost attribute:

[HttpPost]
public ActionResult Save(string name, string salary)
{
    /*Do Stuff here*/

    return View("Message");
}

Upvotes: 1

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38478

You should start by learning about conventions in ASP.NET MVC. You should use models for communicating between controllers and views.

Create a model type first:

public class SalaryModel
{
    public string Name { get; set; }
    public string Salary { get; set; }
}

Create your form by using HTML helpers and strongly typing your view:

@model SalaryModel

<div id="mydiv">
@using (Html.BeginForm("Save", "Game", FormMethod.Post, new { @Id = "Form1" }))
{
    <table border="0">
    <tr>
        <td>Name :</td>
        <td>@Html.TextBoxFor(item => item.Name)</td>
    </tr>

     <tr>
        <td>Salary :</td>
        <td><input name="salary" type="text" /></td>
    </tr>
    <tr>
        <td colspan="2">@Html.TextBoxFor(item => item.Salary)</td>
    </tr>
    </table>
}
</div>

Then you can get the form values inside the model:

[HttpPost]
public ActionResult Save(SalaryModel model)
{
    return View("Message");
}

There's a great tutorial on ASP.NET MVC website that can help you with the basics.

Upvotes: 3

Related Questions