简体   繁体   中英

How to pass textarea value to controller action on the click of a button in asp.net mvc?

In my asp.net application I have a textarea which takes the reviews of the user as input.

<div>
  <textarea name="mytext" id="mytext"></textarea>
</div>

This textarea can be accessed using the id.

I have next defined a button (image button) as follows:

<a class="btn btn-success">Leave a Review</a>

I would like to pass the value of the textarea to a controller action when the Leave a Review button is clicked.

Currently I redirect to a controller action as follows:

<a class="btn btn-success" onclick="localtion.href='@Url.Action("ControllerAction", "ControllerName", new { // pass data here })'">Leave a Review</a>

How can this be achieved, any help on this is appreciated.

You can do it using jquery

     <div>
         <textarea name="mytext" id="mytext"></textarea>
     </div>
     <a class="btn btn-success" onclick="myFunction">Leave a Review</a>

     function myFunction(){
     var myText =$('#mytext').val();
     var number = parseInt(@ViewBag.Number); //Accessing the number from the ViewBag
     alert("Number is: " + number);
     var model = @Html.Raw(@ViewBag.FooObj); //Accessing the Json Object from ViewBag
     alert("Text is: " + model.Text);
    window.location.href = '@Url.Action("ControllerAction", "ControllerName", new { someParam = "myText", viewbagNum = number ,viewbagModelText =  model.Text})'
    }

You can pass parameter like :

 <textarea name="mytext" id="mytext"></textarea>
 <a class="btn btn-success" onclick="LeaveReviewFunc()">Leave a Review</a>

  function LeaveReviewFunc() {
      var textareadata = $("#mytext").val();
      window.localtion.href='@Url.Action("ControllerAction", "ControllerName", new { text : textareadata  })';
  }

And in action:

public ActionResult ControllerAction(string text) {
     //enter code here
}

You can pass value to controller via two ways. 1. Create a form put this textarea into the form tag. 2. Call a Js Method on click of button.In this Js mehtod make a ajax request.

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