Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Asp.Net Core – pass array value from Controller to view by Json after checkbox is checked?

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  class="js-recipient-is-me" 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');
}

});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Html Inputs :

<input type="text" id="mobile" class="js-input-field" name="name" />
<input type="text" id="name" class="js-input-field" name="name" />
<input type="text" id="family" class="js-input-field" 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’ has three values ‘Mobile-name-family’

I want to put userinfo values ​​into inputs…

How is it done?

>Solution :

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" class="js-input-field" name="mobile" />

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading