开发者

Using an HTML button in MVC

开发者 https://www.devze.com 2023-01-08 11:42 出处:网络
I feel a bit stupid asking this, but I just want to know how I can have a html button call a server site action on my controller.

I feel a bit stupid asking this, but I just want to know how I can have a html button call a server site action on my controller.

For example lets say I have a Text Area and a submit button. The idea 开发者_运维百科would be to click the submit button and the text in the text area would get submitted to the Database. Very simple stuff.

Thank you for the help!


in the aspx:

     <%Html.BeginForm("Hello","Home",FormMethod.Post);%> <!--Name of method, name of controller, formmethod -->
        <input type="text" id="userName" maxlength="50" name="userName"/>
        <input id="Submit1" type="submit" value="Say Hello!" />
     <%Html.EndForm();%>
     <h2><%= Html.Encode(TempData["Message"]) %></h2>

In the Controller (HomeController in this example):

public ViewResult Hello(string userName) //note this variable is exactly what is the name of text input on page
        {
            //simple example, take input and pass back out
            TempData["Message"] = "Hello, " + userName;
            return View("Index",TempData);
        }

EDIT: To address additional question about maintaining URL

One method to accomplish "staying in place" as far as your URL is to "overload" the Index method of your controller like below

[AcceptVerbs(HttpVerbs.Post)] //This is KEY <-----
        public ActionResult Index(string userName)
        {
            //simple example, take input and pass back out
            TempData["Message"] = "Hello, " + userName;
            return View("Index",TempData);
        }

Then in your Index.aspx change the Html.Begin Form like below, your just pointing to the default action now

<%Html.BeginForm("Index","Home",FormMethod.Post);%> 

Since you are posting to the controller and not getting(the default index action) the version that is setup to AcceptVerb POST and take the userName string will run and your URL should be maintained


In the view's HTML, the text area and submit button would be part of a form, and that form's action attribute would point to '' and you'd put a part into the same controller that generated that view that checks for POST data. If there's POST data, you'd write it to the database.

The form would look something like this:

<form action='' method='post'>
    <textarea name="text"></textarea>
    <input type="submit" value="Submit"/>
</form>

In the POST, you'll see a variable with a key that matches the name attribute of the textarea (in this case, text). You can read it from there.

If you like, you can also change the action attribute on the form to a URL, in which case you'd write the part that checks the POST data in a controller that that URL points to.

0

精彩评论

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