سؤال

I'm converting an ASP.NET Forms app (that I didn't write) to an MVC 3 app. The ClientScriptManager is used in the old app. ClientScriptManager doesn't exist in MVC 3. What replaced ClientScriptManager? I've done enough reading to know that CSM has something to do with AJAX functionality in ASP.NET; it registers "sets" of js scripts and functions somewhat akin to how EditorTemplates work for sets of similar controls. I'm not necessarily looking to implement a CSM in MVC; I just want to know what practices Microsoft put in place that rendered CSM obsolete.

هل كانت مفيدة؟

المحلول

ASP.Net MVC was designed to give you complete control over the HTML and js, rather than having the framework render these for you, as with ASP.Net. So, nothing really "replaces" the ClientScriptManager. As a result, it is entirely up to you how you handle your js.

You can do something simple like include <script ...> tags to reference inline script or js files in your _Layout.cshtml file, or you could use some sort of JavaScript Loader like RequireJS or come up with your own scheme entirely using "Html Helpers" or something.

MVC 4 introduced the concept of bundling which lets you define collections of scripts as "bundles" and have MVC automatically minify and merge them together for you when you reference them in your Views like this :

@Scripts.Render("~/bundles/jquery")

نصائح أخرى

Below is an example for rendering the JavaScript(Function) from Controller.

Controller

public ActionResult Index(int? id)
{
    ViewBag.MyAlert = "<script type='text/javascript'>MyAlert();</script>";
}

View

<script src="Your Path" type="text/javascript"></script>
@Html.Raw(ViewBag.MyAlert)

JS

function MyAlert() {
    alert('Hi');
}

Below is an example for rendering the JavaScript(File) from Controller.

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("<script src='Your Path' type='text/javascript'></script>");
    filterContext.HttpContext.Response.Write(sb.ToString());
}

So using this approach you do not need to mentioned following code in View.

<script src="Your Path" type="text/javascript"></script>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top