开发者

How to pass value from view to controller

I Have a question.

I need to pass a value in C# and MVC3 to a controller but I don't know h开发者_如何学编程ow.

The code in my view is :

@html.textbox("Name"); 
<input value="Envoyer" type="submit">

How can I get the value of name to my controller, please ?

Thanks


there is another way.

[HttpPost]
public ActionResult Index() {

    string name = Request["name"];
}


Wrap it in a form and have a submit button of some sort to call your Action Method.

<% using (Html.BeginForm("MethodName", "Home", FormMethod.Post)) {%>
     <% Html.Textbox("Name") %> 
     <input value="Envoyer" type="submit" />
<% } %>



[HttpPost]
public ActionResult MethodName(FormCollection col)
{
    string name = col["Name"];
}


<%= Model %>

In MVC 3, you see the <dynamic> set as model by default in your view. Just pass a string as object to the view (return View((object)"Name");) from your controller.

Also see this for a more complex example.

[Edit]

I have got to start reading better :)

Ok, here we go.

The easyest way to do this, is via a <form>. Any input element is posted to your controller where the 'name' attribute will be the variable name (parameter).

Example:

<form action="/Contact/SendMessage" method="post">
    <table>
        <tr>
            <th>Your e-mail adres:</th>
            <td class="inputCell">
                <input id="txtEmail" name="Email" type="text" value="<%= Model %>" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <textarea name="Message" rows="10" style="width: 450px;"></textarea>
            </td>
        </tr>
        <tr>
            <th colspan="2" style="text-align: right;"><input type="submit" id="SendButton" value="Send Message" /></th>
        </tr>
    </table>
</form>

On the controller, you can have your function like:

[AcceptVerbs(HttpVerbs.Post)]
public RedirectResult SendMessage(String Email, String Message)
{
}


Just wrap it in a form, as has already been offered:

@using(Html.BeginForm()) {
    @Html.Textbox("Name")

    <input value="Envoyer" type="submit">
}

And then in your controller action simply declare a parameter with the name Name (assuming this is happening in a view called Index):

[HttpPost]
public ActionResult Index(string Name)
{
    // do whatever with Name
}

Using the FormCollection as has been said is also a perfectly valid option, but this is even easier and a little cleaner, in my opinion.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜