1

I want to create a pretty simple script on the server (A client proxy for server side events). Whats the most common way of render scripts server side using MVC4?

Update after first answer: I want to include for example @Scripts.Render("~/eventAggregation/events") and it should invoke code on my server that generates the Javascript with C# code, also this is for for a lib so I cant do it with a Razor page or MvcController, I want it to be close to SignalR's Hub proxy, I looked at that code but its several hundred lines of codes for injecting a dynamic generated script, must be easier than that?

4

2 回答 2

1

由于您声明不能使用 MvcController 或 Razor 视图,因此您可以更接近金属:IHttpHandler.

所以从写一个开始:

public class MyHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        var response = context.Response;
        response.ContentType = "text/javascript";
        var message = "This is some super dynamic message. The UTC time now is: " + DateTime.UtcNow.ToLongTimeString();
        var js = string.Format("alert({0});", new JavaScriptSerializer().Serialize(message));
        response.Write(js);
    }

    public bool IsReusable 
    { 
        get { return true; } 
    }
}

然后编写相应的路由处理程序:

public class MyHandlerProvider: IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new MyHandler();
    }
}

并在您Application_Start添加一条路线:

protected void Application_Start()
{
    RouteTable.Routes.Add(
        new Route(
            "eventAggregation/events", 
            new MyHandlerProvider()
        )
    );
}

如果您不想手动添加路线,您Application_Start可以使用WebActivator. 只需编写一个静态 Startup 类:

internal static class Startup
{
    public static void Application_Start()
    {
        RouteTable.Routes.Add(
            new Route(
                "eventAggregation/events", 
                new MyHandlerProvider()
            )
        );        
    }
}

然后使用程序集范围的属性:

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MvcApplication1.Startup), "Application_Start")]

现在,您的观点中剩下的就是引用它:

<script type="text/javascript" src="~/eventAggregation/events"></script>
于 2013-05-14T08:19:01.423 回答
0

有捆绑包和 RenderSection 和 @Scripts.Render(

例子:

"@RenderSection("Scripts", true)".

您是否希望将服务器端代码向下传递到您的 UI 层?

例子:

元素的数据属性或 id 并在 JavaScript 中获取它们。

<div id="MightyId" data-name="@item.attribute"></div>

$('#MightyId').data('name')

或在脚本标签中。

var ItemsList = "@item"

或者:

var Items List = @Html.Raw(Json.Encode(object))  
于 2013-05-14T01:21:50.387 回答