Alan Araya
Alan Araya

Reputation: 721

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();
        }

Upvotes: 1

Views: 2425

Answers (1)

Alan Araya
Alan Araya

Reputation: 721

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

Upvotes: 2

Related Questions