简体   繁体   中英

displaying json strings from controller in view over ajax in asp.net core 2 MVC

Im calling an ajax function in a modal when I press a BTN which calls a Controller action and passes a parameter to controller. I now want to return strings as a Json back to the view and display them in the same Modal. Weirdly it worked on my laptop with dependency "System.Web.MVC" but doesnt seem to work in "Microsoft.AspNetCore.Mvc". When returning the Jsons I fill the inputs in the modal with those json strings but on the PC with asp.net core the Inputs just stay empty where on the laptop they get filled.

Controller return type

       return Json(new { Nachname, Vorname, UserName });

Ajax

$(document).ready(function () {
    $("#btnGet").click(function () {
        $.ajax(
            {
                type: "POST",
        url: "@Url.Action("getName", "Home")",
                data: {
                    UserName: $("#txtName").val()
                },
                success: function (result) {
                    $('#infos').show();
                    $('#txtName').addClass("form-control is-valid");
                    $('#InputFirstName').val(result.Vorname);
                    $('#InputLastName').val(result.Nachname);
                    $('#InputFirstName').show();
                    $('#InputLastName').show();
                    $('#labelInfo').show();
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });

    });
});

`

As I mentioned in the comments, your string which is returned to is:

{nachname: "Morf", vorname: "Mischa", userName: "mrfmi"} 

And you're using it as:

$('#InputFirstName').val(result.Vorname);

Here result.Vorname will be undefined so you need to change it as follows:

$('#InputFirstName').val(result.vorname);
...

Could it be a missing parameter in your AJAX call?

Try adding:

dataType: "json"

to your parameters.

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