Home > Software design >  Pass array value from Controller to view by Json after checkbox is checked
Pass array value from Controller to view by Json after checkbox is checked

Time:12-28

I have a check box in the view, I want it to return data from the controller when checked, it is displayed in the view and displaying in the input boxes?

<input   type="checkbox"/>

Javascript :

$('.js-recipient-is-me').change(function () {
    if (this.checked) {
        $('.js-input-field').addClass('disabled');
        $.ajax({
            url: '/Cart/GetUserInfo',
        });
    } else {
        $('.js-input-field').removeClass('disabled');
    }
});

Html Inputs :

<input type="text" id="mobile"  name="name" />
<input type="text" id="name"  name="name" />
<input type="text" id="family"  name="name" />

Controller :

public async Task<JsonResult> GetUserInfo()
{
    CurrentUserId = User.FindFirstValue(ClaimTypes.NameIdentifier);

    var userinfo = await _scope.GetUserInfo(Guid.Parse(CurrentUserId));

    return Json(0);
}

userinfo is a string array and has three values: ["Mobile", "name", "family"]

I want to put userinfo values ​​into inputs...

How is it done?

CodePudding user response:

You need to add a callback to handle the data received from the server. You can do this by using done() after the ajax request.

    $.ajax({
        type: "GET",
        url: '/Cart/GetUserInfo'
    })
    .done( function(data) {
        $('#mobile').val(data[0]);
        $('#name').val(data[1]);
        $('#family').val(data[2]);
    });

You also need to pass the data from the Controller to the view. Currently, it looks like you're always returning 0. Return the userinfo object like this: return Json(userinfo);

public async Task<JsonResult> GetUserInfo()
{
    CurrentUserId = User.FindFirstValue(ClaimTypes.NameIdentifier);
    var userinfo = await _scope.GetUserInfo(Guid.Parse(CurrentUserId));

    return Json(userinfo);
}

You should also give your inputs appropriate names - they're all sharing name which would cause issues with a regualar form submission, eg: <input type="text" id="mobile" name="mobile" />

  • Related