JQUERY ajax passing value from MVC View to Controller

243,623

Solution 1

Try using the data option of the $.ajax function. More info here.

$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatus) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

Solution 2

Here's an alternative way to do the same call. And your type should always be in CAPS, eg. type:"GET" / type:"POST".

$.ajax({
      url:/ControllerName/ActionName,
      data: "id=" + Id + "&param2=" + param2,
      type: "GET",
      success: function(data){
            // code here
      },
      error: function(passParams){
           // code here
      }
});

Another alternative will be to use the data-ajax on a link.

<a href="/ControllerName/ActionName/" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#_content">Click Me!</a>

Assuming u had a div with the I'd _content, this will call the action and replace the content inside that div with the data returned from that action.

<div id="_content"></div>

Not really a direct answer to ur question but its some info u should be aware of ;).

Solution 3

$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatu`enter code here`s) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

Solution 4

View Data
==============


 @model IEnumerable<DemoApp.Models.BankInfo>
<p>
    <b>Search Results</b>
</p>
@if (!Model.Any())
{
    <tr>
        <td colspan="4" style="text-align:center">
            No Bank(s) found
        </td>
    </tr>
}
else
{
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Address)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Postcode)
            </th>
            <th></th>
        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Address)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Postcode)
                </td>
                <td>
                    <input type="button" class="btn btn-default bankdetails" value="Select" data-id="@item.Id" />
                </td>
            </tr>
        }
    </table>
}


<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#btnSearch").off("click.search").on("click.search", function () {
            if ($("#SearchBy").val() != '') {
                $.ajax({
                    url: '/home/searchByName',
                    data: { 'name': $("#SearchBy").val() },
                    dataType: 'html',
                    success: function (data) {
                        $('#dvBanks').html(data);
                    }
                });
            }
            else {
                alert('Please enter Bank Name');
            }
        });
}
});


public ActionResult SearchByName(string name)
        {
            var banks = GetBanksInfo();
            var filteredBanks = banks.Where(x => x.Name.ToLower().Contains(name.ToLower())).ToList();
            return PartialView("_banks", filteredBanks);
        }

        /// <summary>
        /// Get List of Banks Basically it should get from Database 
        /// </summary>
        /// <returns></returns>
        private List<BankInfo> GetBanksInfo()
        {
            return new List<BankInfo>
            {
                new BankInfo {Id = 1, Name = "Bank of America", Address = "1438 Potomoc Avenue, Pittsburge", Postcode = "PA 15220"  },
                new BankInfo {Id = 2, Name = "Bank of America", Address = "643 River Hwy, Mooresville", Postcode = "NC 28117"  },
                new BankInfo {Id = 3, Name = "Bank of Barroda", Address = "643 Hyderabad", Postcode = "500061"  },
                new BankInfo {Id = 4, Name = "State Bank of India", Address = "AsRao Nagar", Postcode = "500061"  },
                new BankInfo {Id = 5, Name = "ICICI", Address = "AsRao Nagar", Postcode = "500061"  }
            };
        }

Solution 5

I didn't want to open another threat so ill post my problem here

Ajax wont forward value to controller, and i just cant find an error :(

-JS

<script>
        $(document).ready(function () {
            $("#sMarka").change(function () {
                var markaId = $(this).val();
                alert(markaId);
                debugger
                $.ajax({
                    type:"POST",
                    url:"@Url.Action("VratiModele")",
                    dataType: "html",
                    data: { "markaId": markaId },
                    success: function (model) {
                        debugger
                        $("#sModel").empty();
                        $("#sModel").append(model);
                    }
                });
            });
        });
    </script>

--controller

public IActionResult VratiModele(int markaId = 0)
        {
            if (markaId != 0)
            {
                List<Model> listaModela = db.Modeli.Where(m => m.MarkaId == markaId).ToList();
                ViewBag.ModelVozila = new SelectList(listaModela, "ModelId", "Naziv");
            }
            else
            {
                ViewBag.Greska = markaId.ToString();
            }

            return PartialView();
        }
Share:
243,623
Admin
Author by

Admin

Updated on July 19, 2020

Comments

  • Admin
    Admin almost 4 years

    What I want is to pass the value of txtComments from View (using jquery/ajax) to Controller.

    The problem is the ajax/jquery doesn't accept script tags as string. Meaning, when I input any script/html tag in the txtComments the ajax goes to the error function and not being able to go in the controller.

    Here is the jQuery:

            $('#btnSaveComments').click(function () {
                var comments = $('#txtComments').val();
                var selectedId = $('#hdnSelectedId').val();
    
                $.ajax({
                    url: '<%: Url.Action("SaveComments")%>?id=' + selectedId + '&comments=' + escape(comments),
                    type: "post",
                    cache: false,
                    success: function (savingStatus) {
                        $("#hdnOrigComments").val($('#txtComments').val());
                        $('#lblCommentsNotification').text(savingStatus);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        $('#lblCommentsNotification').text("Error encountered while saving the comments.");
                    }
                });
            });
    

    Here is the controller:

            [HttpPost]
            public ActionResult SaveComments(int id, string comments){
                 var actions = new Actions(User.Identity.Name);
                 var status = actions.SaveComments(id, comments);
                 return Content(status);
            }
    

    I also tried $('#txtComments').serialize() instead of escape(comments) but still the same.

  • Admin
    Admin over 12 years
    thanks! it worked. i just revised the code to data:{ 'id': selectedId, 'comments': escape(comments)} so jquery/ajax will accept it.
  • Felipe Oriani
    Felipe Oriani almost 7 years
    Would be nice if you add some comments about the answer!
  • carl
    carl over 5 years
    @tobias86 I have 30+ parameters, should I do the same thing as you have presented? I tried using an object and use JSON.stringify. However, sometimes it is giving null values. It happens intermittently. So we are trying to eliminate the object parameter and send every parameter one by one to avoid that intermittent issue. Do you have any suggestion to better address this problem? Thanks.
  • Burkely91
    Burkely91 almost 5 years
    Hi, be sure to explain what your code does/how it answers the question etc. A code snippet standing alone may not be enough information for all users! :)
  • Insane Shadow
    Insane Shadow almost 5 years
    I apologize, this app should contain two Select tags, when you pick something like for example 'Audi' from first Select tag, second one should 'put' Audi's models.
  • Insane Shadow
    Insane Shadow almost 5 years
    link Something like this, i tried to use his code but it didn't work
  • Burkely91
    Burkely91 almost 5 years
    You can edit your answer as opposed to adding comments