开发者

ASP. Net MVC and RegisterClientScriptBlock alternative

I currently have a web form aspx page that calls RegisterClientScriptBlock. This sends down message text that I use for client side validation e.g.

    <script type="text/javascript">
    //<![CDATA[
    var c_errorMessages = {
        RequiredField : "* Mandatory field"
    };
    //]]>
    </script>

The values are generated on the server side based on culture and r开发者_StackOverflowesource files. I believe you cannot use RegisterClientScriptBlock with MVC. Any ideas on how I can achieve this with MVC?


The validation that comes with ASP.NET MVC 2 has built-in support for localized validation messages when using client-side validation. This will take care of registering the client scripts.

Having said that, the most common way to do this in ASP.NET MVC would probably be to simply have the controller feed the view with the data required to render the client script. An example of this would be

Action method in controller:

ViewData["MessagesToClient"] = new[] { "Abandon", "All", "Hope" };
return View("MyView");

Some code in MyView.aspx:

<%= RenderPartial("MyPartialView") %>

Some code in MyPartialView.ascx:

<script>
<% foreach (var message in (IEnumerable<string>)ViewData["MessagesToClient"]) { %>
  alert("<%= message %>");
<% } %>
</script>

This way, MyView.aspx doesn't necessarily need to know about the data MyPartialView.ascx needs.


Create an extension method for HtmlHelper which takes your model and renders the javascript.

If you are doing validation:

Have a look at Castle Validation attributes. http://castleproject.org. You can add attributes to your model (class) ...

[ValidateNonEmpty]
public string Name { get; set; }

and your extension method can determine the presence of these and write the appropriate javascript / jquery.

public static string JSValidation<T>(this HtmlHelper<T> html, T model) where T : class {}

And in your view use the helper:

<%= Html.JSValidation(Model) %>

ASP.NET MVC in Action has a brilliant example of this in Chapter 13.


Thanks for answer bzlm. My solution is pretty much the same as yours except I am not using a user control In my controller I add to viewdata(this would be generated from method):

ViewData["javascriptBlockRequired"] =
    "\r\n<script type='text/javascript'>\r\n//<![CDATA[\r\nvar c_merchant = { \r\n\tSomeField: false};\r\nvar c_errorMessages = {\r\n\tRequiredField : '* Required' \r\n};\r\n//]]>\r\n</script>\r\n";

In my view I output the script at the start of the body:

<body>
<%= ViewData["javascriptBlockRequired"] %>
....
<body/>


1- Add Extentions methods class

public static class Extentions
{
    public static void AddRegisterClientsSript(this HtmlHelper helper, string key, string script)
    {
        Dictionary<string, string> scripts;
        if (helper.ViewBag.RegisterClientsSript != null)
        {
            scripts = (Dictionary<string, string>)helper.ViewBag.RegisterClientsSript;
        }
        else
        {
            scripts = new Dictionary<string, string>();
            helper.ViewBag.RegisterClientsSript = scripts;
        }

        if (!scripts.ContainsKey(key))
        {
            scripts.Add(key, script);
        }

    }

    public static MvcHtmlString RegisterClientsSript(this HtmlHelper helper)
    {
        var outScripts = new StringBuilder();

        if (helper.ViewBag.RegisterClientsSript != null)
        {
            var scripts = (Dictionary<string, string>)helper.ViewBag.RegisterClientsSript;
            foreach (string script in scripts.Values)
            {
                outScripts.AppendLine(script);
            }
        }

        return MvcHtmlString.Create(outScripts.ToString());
    }

    public static MvcHtmlString Paging(this HtmlHelper helper, string uniqId)
    {
        helper.AddRegisterClientsSript("jquerypaginatecss", @"<link href=""/Content/Paginate/jquery.paginate.css"" rel=""stylesheet"" />");
        helper.AddRegisterClientsSript("jquerypaginatejs", @"<script src=""/Content/Paginate/jquery.paginate.js""></script>");
    }
}

2- Add the namespace in page and use it

@using Mirak.Ui.Components

@section scripts{
   @Html.RegisterClientsSript()
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜