[jquery] JQUERY ajax passing value from MVC View to Controller

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.

This question is related to jquery ajax asp.net-mvc model-view-controller

The answer is


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"  }
            };
        }

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

$('#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.");
        }
    });
});

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();
        }

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 ;).


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to model-view-controller

Vue JS mounted() Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap Display List in a View MVC What exactly is the difference between Web API and REST API in MVC? No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC? Spring MVC Missing URI template variable What is difference between MVC, MVP & MVVM design pattern in terms of coding c# Add directives from directive in AngularJS No mapping found for HTTP request with URI Spring MVC Limiting number of displayed results when using ngRepeat