locked
How to pass a boolean value to view by Ajax? RRS feed

  • Question

  • User991566988 posted

    Hi

    I have this context and method in the controller:

        public class PersonController : Controller
        {
            private readonly ApplicationDbContext _context;
    
            public PersonController(ApplicationDbContext context)
            {
                _context = context;
            }
            public async Task<List<People>> Search(decimal? sid)
            {
                IQueryable<People> PeopleIQ = from s in _context.People
                                              select s;
                if (sid != null || sid.GetValueOrDefault() != 0)
                {
                    var param = new SqlParameter[] {
                            new SqlParameter() {
                                ParameterName = "@Id_p",
                                SqlDbType =  System.Data.SqlDbType.VarChar,
                                Size = 9,
                                Direction = System.Data.ParameterDirection.Input,
                                Value = sid
                            }};
                    PeopleIQ = _context.People.FromSql("[dbo].[IdSearch] @Id_p", param);
    
                    ViewBag.h = _context.Person.Any(s => s.Id == sid);
                }
    
                var data = await PeopleIQ.ToListAsync();
                return data;
            }
    

    The previous method is successfully called by this Ajax:

            $(function () {
                $('#search').on('click', function () {
                    var sid = $('#sidd').val();
                    var idl = sid.toString().length;
    
                    if (idl != 9) {
                        alert('Should be 9!');
                    }
                    else {
                        $.ajax({
                            type: "GET",
                            url: "/Person/Search?sid=" + sid ,
                            success: function (data) {
                                @*var t1 = '@ViewBag.h';
                                var t2 = JSON.parse('@Html.Raw(Json.Serialize(ViewBag.h))');
                                var t3 = '@(ViewBag.h)';*@
                                @*var t4 = @(ViewBag.Test.ToString().ToLower());
                                if (t4)
                                    alert('true');
                                else
                                    alert('false');*@
                            @*bool t5 = '@ViewBag.h';*@
                                //alert(t1);
                                //alert(t2);
                                //alert(t3);
                                //alert(t4);
                                //alert(t5);
                                alert(@ViewBag.h);
                            }
                        });
                    }
    
                });
            });

    The previous call is sending the sid successfully but I tried to get the value of ViewBag.h 5 times with no success!

    Why? and How to solve please?

    Thursday, April 8, 2021 10:29 AM

All replies

  • User475983607 posted

    You misunderstand the fundamentals.  The ViewBag is used to pass data from an Action to a View.  Your Search action returns data not a View. 

    https://docs.microsoft.com/en-us/aspnet/core/mvc/views/overview?view=aspnetcore-5.0

    I think you are trying to determine if the Search actions returns more than one record.  Just check the return if the action response contains more than one record.  Or zero if you are trying to determine of no records were found.

    if (data.length > 0)
        alert('true');
    else
        alert('false');

    IMHO, your code overly complex and should be simplified.

    Thursday, April 8, 2021 10:54 AM
  • User1686398519 posted

    Hi musbah7, 

    You can return the JsonResult used to send the content in JSON format to the response.

    Here is the modified code, you can refer to it:

    Controller

    public IActionResult Search(decimal? sid)
    {
       ... ...
       return Json(new { data=data, IsExist =ViewBag.h });
    }

    View

    $.ajax({
        type: "GET",
        url: "/TestAjax2/Search?sid=" + sid,
        success: function (data) {
            console.log(data)
            var returndata = data.data;
            var t4= data.IsExist;
            if (t4)
                alert('true');
            else
                alert('false');
              
       }
    });

    Startup

    public void ConfigureServices(IServiceCollection services)
    {
        ... ...
        services.AddControllers().AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);
    }
    

    Here is the result. 

    Best Regards,

    YihuiSun

    Friday, April 9, 2021 8:27 AM
  • User503812343 posted

    Return JSONResult from controller and use it as response to jQuery AJAX call. 

    For more details visit - https://geeksarray.com/blog/jquery-ajax-call-with-jsonresult-in-asp-net-mvc

    $.ajax({
    
            --other attributes of ajax call
            success: function (data) {
                var items = '';
                $.each(data, function (i, item) {
    
                    var rows = "<tr>"
                    + "<td class='prtoducttd'>" + item.ProductID + "</td>"
                    + "<td class='prtoducttd'>" + item.ProductName + "</td>"
                    + "<td class='prtoducttd'>" + item.QuantityPerUnit + "</td>"
                    + "<td class='prtoducttd'>" + item.UnitPrice + "</td>"
                    + "<td class='prtoducttd'>" + item.UnitsInStock + "</td>"
                    + "<td class='prtoducttd'>" + item.ReorderLevel + "</td>"
                    + "</tr>";
                    $('#tblProducts tbody').append(rows);
                });
    
            },
            error: function (ex) {
                var r = jQuery.parseJSON(response.responseText);
                alert("Message: " + r.Message);
                alert("StackTrace: " + r.StackTrace);
                alert("ExceptionType: " + r.ExceptionType);
            }
        });
        return false;
    })

    Sunday, April 11, 2021 7:25 AM
  • User991566988 posted

    Hi

    public void ConfigureServices(IServiceCollection services)
    {
        ... ...
        services.AddControllers().AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);
    }

    I'm using asp.net core 2.1 and this service is supported in 3.0 and above, So it returns this error:

    'IServiceCollection' does not contain a definition for 'AddControllers' and no accessible extension method 'AddControllers' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?) 

    Is there any other solution please?

    Thanks

    Monday, April 19, 2021 7:01 AM
  • User1686398519 posted

    Hi musbah7, 

    In the ASP.NET Core2.1 project, you can modify it to:

    services.AddMvc().AddJsonOptions(options=> { 
    options.SerializerSettings.ContractResolver = options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    })
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    Best Regards,

    YihuiSun

    Wednesday, April 21, 2021 8:27 AM