Question

i wrote behind code. but Viewbag.message will show null in alert message .myvar is a variable. i used breakpoint , myvar will set by Viewbag.message correctly. but it will be shown null in alert .

         <script src="~/Scripts/jquery-1.7.1.js"></script>
         <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

   @{string myvar = ViewBag.AlertMessage;}

   @using (Ajax.BeginForm("action", "controller", new AjaxOptions { HttpMethod = "Post",    OnSuccess = "Messsage" }))
                   {

  <script type="text/javascript">

   function Messsage() {

    alert('@ViewBag.AlertMessage');    //infact, it shows alert('');
    }


  </script>
Was it helpful?

Solution

<script type="text/javascript">
function Messsage() {
    alert('@myvar');    // should show "hello there"
}
</script>
 @using (Ajax.BeginForm("AjaxAction", "Home", new AjaxOptions { HttpMethod = "Post", OnSuccess = "Messsage" }))
{

    <script type="text/javascript">
        function Messsage() {

            alert("@ViewBag.AjaxMessage");
        }
    </script>

    <input type="submit" value="Submit" />

} 

OTHER TIPS

is the ViewBag.AlertMessage being defined in the controller action ?

you can replace the data by

@{string myvar = "hello there !";}

<script type="text/javascript">
    function Messsage() {
        alert('@myvar');    // should show "hello there"
    }
</script>

or define your viewbag item in the action method behind the result

public ActionResult Index() {
    ViewBag.AlertMessage = "hello there !"
    return View();
}

Try setting the value for ViewBag.AlertMessage in controller action that returns the view on which you have defined the Ajax.Begin form.

eg

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            ViewBag.AlertMessage = "AjaxMessage.";

            return View();
        }
     }

on Index view i have placed the following code, calling AjaxAction on Home Controller.

  @using (Ajax.BeginForm("AjaxAction", "Home", new AjaxOptions { HttpMethod = "Post", OnSuccess = "Messsage" }))
    {

        <script type="text/javascript">
            function Messsage() {

                alert("@ViewBag.AjaxMessage");
            }
        </script>

        <input type="submit" value="Submit" />

    } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top