Search code examples
c#asp.net-mvcviewbagtempdata

MVC C# pass information from controller to view


I have a problem, that I have a bit of trouble figuring out. I need to pass some data, a String, from a Controller to an already strongly typed view. I'm currently working in a live environment, sort of, so I don't completly know about the structure or what other Controllers/views are passed, except the ones I'm working in.

I'm guessing there's more than one, since a simple ViewBag doesn't seem to work. I've tried storing the string in the viewbag, but that didn't show up on the view. For clarification, I used:

Viewbag.PassedString = "This is a test"

.

<div> @Viewbag.PassedString </div>

Anyway, like I said that didn't work, I'm guessing the data was lost in the process. Next, I tried using TempData, but that doesn't work either atm.

Am I forgetting something important? Are there any alternatives to get the job done?


Solution

  • You have typo here..name of property should be same both side for example you have made "p" small in your view instead of that,

    Try

    <div> @Viewbag.PassedString </div>
    

    Update :-

    From your query I am understanding that you are returing json, ViewBag is used to pass data from the controller to the View Engine. in this case you are returning json, no view, so to make Viewbag work it should return a view.

    One more Update :-

    Well in your code I guess you can pass object here:-

    write

     return Json(dataYouWantToPass, JsonRequestBehavior.AllowGet);
    

    instead of

    return Json("", JsonRequestBehavior.AllowGet);
    

    and in your jquery you can get as below in success call :-

    $.ajax({
                    cache: false,
                    type: "GET",
                    url: "@(Url.Action("GetDownloadLink", "Export"))",
                    data: { "stadId": stadId, "catId": catId },
                    success: function(data) {
                        $('#bezig-tekst').html('');
                        $('#download-link').show();
                        alert(data); ////here you get the data you sent from controller.
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        alert('Failed to retrieve xml.');
                    }
                });
            });