How to pass multiple input text value to method in controller

I having 3 textbox and I want to send value enter over there to controller method

<input class="form-control" type="text" id="id" name="id">
<input class="form-control" type="text" id="id1" name="id1">
<input class="form-control" type="text" id="id2" name="id2">

@Html.ActionLink("Send", "MethodNameInController", "ColtrollerName", new { id= $('#id').val(), 
id1= $('#id1').val(), id2= $('#id2').val()})

and in controller public ActionResult MethodNameInController(int id, string id1, string id2) { //some text here }

but it’s sending null value

Answer

If you want to stay on the same view or redirect to another url after, instead of using @Html.ActionLink() try passing the values to the controller using an ajax call.

function submitAjax(){

        //purely for readability
        var id = $('#id').val();
        var id1 = $('#id1').val();
        var id2 = $('#id2').val();

        //ajax call
        $.ajax({
        url: "/ControllerName/MethodNameInController",
        data: { id: id, id1: id1, id2: id2 },
        success: function (result) {
            //handle something here
        }
    });
};
<input class="form-control" type="text" id="id" name="id">
<input class="form-control" type="text" id="id1" name="id1">
<input class="form-control" type="text" id="id2" name="id2">

<button type="button" onclick="submitAjax()">submit</button>

If the method does some processing and then returns you to a different view, you could do a form submit.

function submitForm(){
      var $form = $("#idForm");
      //optional validation
      
      $form.submit();
};
<form id="idForm" class="form-horizontal" asp-controller="ControllerName" asp-action="MethodNameInController" >
  <input class="form-control" type="text" id="id" name="id">
  <input class="form-control" type="text" id="id1" name="id1">
  <input class="form-control" type="text" id="id2" name="id2">

  <!-- type="button" prevents the from from submitting so you can do validation checks in the js -->
  <button type="button" onclick="submitForm()">submit</button>
</form>

Leave a Reply

Your email address will not be published. Required fields are marked *