简体   繁体   中英

Asp.net core 1.0 - Write javascript on Response

How to write a javascript result at Response.Body on MVC6/Asp.net core 1.0?

In my case, I want to render a script to call a notification for the client, and don´t want to put a code in my view to check wheter a new notification exists on ViewData (for exemple).

If I do this like:

   var bytesWrite = GetBytes(script);
   await HttpContext.Response.Body.WriteAsync(bytesWrite, 0, bytesWrite.Length);

The result is the script rendered as HTML text.

UPDATE:

This might clear things out. I would like to return my View() as result. BUT, write on the Response.Body (obivious it will be encapsulated later) a "<script> Alert("Hey")</script>"

 public IActionResult Popup()
        {
            //logic
            //.....
            //var script = ProduceNotification();
            //

            //Render Notifications
            var bytesWrite = GetBytes(script);
            await HttpContext.Response.Body.WriteAsync(bytesWrite, 0, bytesWrite.Length);

            //Return de view normally. It doesn´t know about any notifications beeing returned
            return View();
        }

I´ve managed to do this with Components:

http://www.strathweb.com/2015/07/viewcomponents-asp-net-5-asp-net-mvc-6/ http://blog.2mas.xyz/asp-net-5-view-components/

The implementation steps are:

  • Create a custom component that reads mesages stored on HttpContext.Items
  • Create a View shared that others will inherit and on that view call you Component
  • On the component return a view that only render the script calls

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