简体   繁体   中英

How to call a JavaScript function from controller in MVC 4?

I am new to MVC, so please ignore my mistakes. I want to call a JavaScript function from controller, I tried myself and searched to call JavaScript function but did not find any reasonable solution. Please help Here is my code.

 [AllowAnonymous]
    public ActionResult Index()
    {
        LogisticQuote lq = new LogisticQuote();
        if (Request.QueryString["token"] != null)
        {
            byte[] byteArray = Convert.FromBase64String(Request.QueryString["token"]);
            string values = System.Text.Encoding.UTF8.GetString(byteArray);
            EdgeMoveService serivice = new EdgeMoveService();
            Edge.Move.Common.Status.ServiceStatus serviceStatus = serivice.GetLogisticQuote(values.Split('&')[1].Split('=')[1], String.Empty, new TenantId(values.Split('&')[0].Split('=')[1]), "", 1, 1, new SaveId(values.Split('&')[2].Split('=')[1]), out lq);
            if (serviceStatus.IsOkay)
            {
                TimeSpan difference = (DateTime.Now.Subtract(lq.CreatedTimeStamp));
                if (difference.TotalHours <= 24)
                {
                    if (!lq.IsExpire)
                    {
                        return View("QuoteDetails", lq);
                    }
                    else
                    {
                        ViewBag.Message = "alertError('" + String.Empty + "');";
                        return View("ExpireLinkNotification", lq);
                    }
                }
                else
                {
                    return View("ExpireLinkNotification", lq);
                }
            }
        }
        return View("Startup", lq);
    }

This is not a good practice.

You should avoid messing up javascript in you controllers code, thats what MVC is built for. Separation of concerns.

What you can do? Pass the message to be displayed in the ViewBag or ViewData. Receive this message in the script tag at the view side (store it in a javascript variable). Check if message is non-empty show it in alert.

View.cshtml

<script>
var msg='@ViewBag.Message';
if(msg && msg.length>0)
  alert(msg);
</script>

You have two options to do that.

Option #1

Call the controller method from using jquery ajax call and then in the success method you can fire your js method.

Option #2

In the document.ready event of your cshtml page, you can do like this

$.document.ready(function(){
   var msg = '@ViewBag.Message'
   if(msg != undefined && msg !== "")
       alert(msg);
});

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