Viewbag is null in alert

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>

Answers


<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" />

} 

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" />

    } 

Need Your Help

Delphi 7 - Check if server is online

delphi delphi-7 status remote-server

I have a program created in Delphi 7 that uses ftp downloading.

VBA: How to run another application from MS Access

shell ms-access vba

I've been trying to get this issue figured out, and it seems that I cannot find the solution to the problem anywhere. Here was the first part: VBA Shell command always returns &quot;File Not Found&...