Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c# - ASP.NET MVC 3 Razor: Passing Data from View to Controller

I'm brand new to all things .NET. I have a very basic web page with an HTML form. I want 'onsubmit' to send the form data from the View to the Controller. I've seen similar posts to this but none have answers involving the new-ish Razor syntax. What do I do with 'onsubmit', and how do I access the data from the Controller? Thanks!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can wrap your view controls you want to pass in Html.Beginform.

For example:

@using (Html.BeginForm("ActionMethodName","ControllerName"))
{
 ... your input, labels, textboxes and other html controls go here

 <input class="button" id="submit" type="submit" value="Submit" />

}

When Submit button is pressed everything inside of of that Beginform will be submitted to your "ActionMethodName" method of the "ControllerName" controller.

ON the controller side you can access all received data from the view like this:

public ActionResult ActionMethodName(FormCollection collection)
{
 string userName = collection.Get("username-input");

}

collection object above will contain all your input entries that we submitted from the form. You can access them by name just like you would access any array: collection["blah"] or collection.Get("blah")

You can also pass parameters to your controllers directly without sending the entire page with FormCollection:

@using (Html.BeginForm("ActionMethodName","ControllerName",new {id = param1, name = param2}))
{
 ... your input, labels, textboxes and other html controls go here

 <input class="button" id="submit" type="submit" value="Submit" />

}

public ActionResult ActionMethodName(string id,string name)
{
 string myId = id;
 string myName = name;

}

Or you can combine both of these methods and pass specific parameters along with the Formcollection. It's up to you.

Hope it helps.

edit: while I was writing other users referred you to some helpful links as well. Take a look.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...