Dynamically Generated JavaScript, CSS in ASP.NET MVC

Dynamically generated Javascript, CSS in ASP.NET MVC

The best solution so far I found for that is the following:

Dynamic Javascript and CSS in ASP.NET MVC using Razor Views

You just create views: CurrentUserOverrides.css.cshtml, ContactViewModel.js.cshtml. This views will contain single HTML block (<script> or <style>), so IntelliSense works fine. Then you create controller that renders that view, trims the root tag and return content with appropriate content type.

Generate javascript file on the fly in asp.net mvc

You could define a controller action:

public ActionResult Data()
{
// Obviously this will be dynamically generated
var data = "alert('Hello World');";
return JavaScript(data);
}

and then:

<script type="text/javascript" src="<%= Url.Action("Data", "SomeController") %>"></script>

If you have some complex script that you don't want to generate in the controller you could follow the standard MVC pattern by defining a view model:

public class MyViewModel
{
... put required properties
}

a controller action which would populate this view model and pass it to the view:

public ActionResult Data()
{
MyViewModel model = ...
Response.ContentType = "application/javascript";
return PartialView(model);
}

and finally a view which in this case will be the javascript representation of the view model (~/Views/SomeController/Data.ascx):

<%@ Control 
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<MyViewModel>" %>
alert(<%= new JavaScriptSerializer().Serialize(Model.Name) %>);

Does anyone use ASP.net (webforms) to dynamically generate javascript and/or css files?

I've used a HTTPHandler to send back dynamic javascript before. But not something that inherits from System.Web.UI.Page.

Using a HTTPHandler and an ASHX or AXD is the "ASP.Net" way to send back resources dynamically.

Create Dynamic Elements that are MVC Format

Thank you GregH for your help! The article you posted was VERY helpful: haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

Have a Class (forgot to post this earlier, but it was there)

    public class Contact
{
public string Name { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
}

Properly Format NAMES (not ids) in HTML
instead of "id=email1" we used "name = 1.email". We also did the same thing for id, but that wasn't the fix.

function addRow(tableID, idNumber) {

var table = document.getElementById(tableID);

var rowCount = table.rows.length;
var row = table.insertRow(rowCount);

var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.id = "[" + idNumber + "].Name";
element2.name = "[" + idNumber + "].Name";
element2.className = "form-control";
cell2.appendChild(element2);

Update the Controller by adding a new method

public ActionResult ExampleName(List<Contact> contacts)
{

var X = contacts;

return View();
}


Related Topics



Leave a reply



Submit