dsi
dsi

Reputation: 3359

How to pass value between two views (common controller) in MVC

Below is the structure of related section of my query:

  AccountController
  {

 [HTTPGET]
 getDetail(int ID)
 {    
  ViewBag.classID = ID;
 }
 }

cshtml razor "view1"
 --------------
   //calling to getDetail(id) and it set the ViewBag.classID.

cshtml razor "view2"
 --------------
  <script type="text/javascript">
$(window).load(function () {
        alert('@ViewBag.classID);   //PROBLEM: gives me empty value everytime even though set from another view.
});

controller is common for both the views.

Problem: view1 has requred to controller and set the CLASSID into viewbag. Now, on jquery load event of view2, i want to access viewBag value but it is not available. I need to render the cshtml based on value exists on viewbag.classID.

Please suggest me if any alternative or best appraoch or how to correct this.

thank You

Upvotes: 0

Views: 1054

Answers (1)

ramiramilu
ramiramilu

Reputation: 17182

Instead of using ViewBag (Viewbag only persists up until rendering of the view, and once View is rendered ViewBag data is lost), you can return the class ID as JSON and use it in your JQuery like shown below. Lets say you have following controller action -

    [HttpGet]
    public ActionResult getDetail(int id)
    {
        return Json(id + " New", JsonRequestBehavior.AllowGet);
    }

Then you can call this action using JQuery in following way -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>

<script>
    function submitForm() {
        jQuery.ajax({
            type: "GET",
            url: "@Url.Action("getDetail")" + "/" + "123", // Get your 123 dynmically here if you want
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                alert(data);
            },
            failure: function (errMsg) {
                alert(errMsg);
            }
        });
    }
</script>

<input type="button" value="Click" onclick="submitForm()" />

And when you click the button, you get an Alert with Json returned data. You can call this JQuery AJAX GET in any event, for example onload of document etc.

Output would be -

enter image description here

NOTE:

If you do not want to follow above approach, then you can use Session variable to store and retrieve information.

EDIT Use TempData - which helps to maintain data when you move from one controller to other controller or from one action to other action.

Upvotes: 1

Related Questions