简体   繁体   中英

passing parameters from HTML form of View page to the controller

i am working in MVC. I have a View say view1 which consist of a HTML Form as given below:

    <form action='/Exercise/Exercise4_SubmitForm' method="post">
    Name: <input type="text" name="name" /><br />
    Emp: <input type="text" name="id" /><br />
    DateofBirth: <input type="text" name="Dateofbirth" /><br />
    Age: <input type="text" name="age" /><br />
    .
    so on
    .
    .
    <input type="submit" name="submit" value="Save" />
    </form>

I have 17 textboxes from which i have mentioned only 4 above.

Now mvc action method must be

    public ActionResult Exercise4(string name, string code, string age, string dateofBirth,...)
    {
      //my code here
    }

My question is that Is there any way by which i dont have to specify each 17 parameters in my mvc action method as given above. Because it will be possible to have 70 parameter next time then specifying each parameter is very tedious work. "I dont want to use HTML Helpers."

Pls help me!!!

Create a Model

public class YourModel
{
    public string name {get;set;}
    public string code {get;set;}
    public string age {get;set;}
    public string date {get;set;}
    .
    .
    .
}

Then, in the top of the view put

@model Namespace.YourModel

After that switch all your inputs with

@Html.EditorFor(m => m.name)
@Html.EditorFor(m => m.code)
@Html.EditorFor(m => m.age)
@Html.EditorFor(m => m.date)

If your unsure on how to do this last part, create a new View and check the Create a strongly-typed view and choose your model out of the combobox. Select also a Scaffold Template accordingly to what you need. Is that a form to insert, edit, delete, list....

The action that receives the Post will recieve your model instead

public ActionResult Exercise4(YourModel model)
    {
      //my code here
    }

If I were you I'd look into: http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-5 first

The fact is that the fields in your form would then have to be a part of a Model (your're using MVC right?) and then the post will contain your Model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM