Search code examples
javascriptc#asp.net-mvcviewbag

Why Viewbag not show in asp.net mvc view page?


I'm beginner in asp.net mvc,write this java script code for fetch any data from controller:

 $.ajax({
    url: '@Url.Action("CallService", "MyScore")',
    type: 'GET',
    dataType: 'json',
    cache: false,
    data: {
        'id': 29
    },
    success: function(color) {
        //alert(color);
    },
    error: function() {
        alert('Error occured');
    }
}); 

and write this action in controller:

[HttpGet]
        public ActionResult CallService(string id)
        {

            var idNum = Convert.ToInt32(id);

            string color = idNum.ToString();
            ViewBag.Myfamily = "razzaqi";

            return Json(color, JsonRequestBehavior.AllowGet);
        }


in view page write this code:

<h1> Hello Dear @ViewBag.Myfamily</h1>


when i run the project <h1> Hello Dear @ViewBag.Myfamily</h1> not show me ,but i think show me this output:

Hello Dear razzaqi

Solution

  • You are returning JSON not ViewBag. You need to send the "razzaqi" to as part of JSON object. Set up HTML as

    <h1> Hello Dear <span id='familyname'></span></h1>
    

    Modify You controller to return myfamily as part of JSON object.

    [HttpGet]
    public ActionResult CallService(int id)
    {
        string color = id.ToString();
    
        return Json(new {
            color = color
            myfamily = "razzaqi"
        }, JsonRequestBehavior.AllowGet);
    }
    

    Consume the result like

    $.ajax({
        url: '@Url.Action("CallService", "MyScore")',
        type: 'GET',
        dataType: 'json',
        cache: false,
        data: { 'id': 29 },
        success: function (data) {
            $('#familyname').text(data.myfamily)
        },
        error: function () {
            alert('Error occured');
        }
    });