简体   繁体   中英

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

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');
    }
});

The Viewbag object is filled into the view, server side when making the view. Your ajax call contacts the server asking about Json data after the view is already made .

So you are too late passing objects to your viewbag if you do it this way...


There are however some workarounds/solutions for this problem:

  1. Let the Controller return the variable in the Json it's returning.
    • Simple, efficient way to get the data you need
    • Html helpers etc. Won't work however and sometimes you just need that horrible viewbag...
  2. Reload a partialview when doing the ajax call.
    • Takes more time to implement, You'll have to create a new action and partialview.
    • Good when you want more content to change on the call and want to use html helpers etc.

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