Bob Tway
Bob Tway

Reputation: 9603

How to render a string into an ASP.NET MVC view Javascript wrapped in quotes

In the JQuery Validate plugin, you can validate file extensions like this:

 $("#my-form").validate({
        rules: {
            file: {
                required: true,
                extension: "xls|csv"
            }
        });

I have a list of valid extensions in my MVC application that I use server side, and I thought it'd be neat to only maintain it in one place. So I tried to do this:

 $("#my-form").validate({
        rules: {
            file: {
                required: true,
                extension: @string.Join("|", new FileHelper().ValidFileExtensions))
            }
        });

But that fails because it's not wrapped in quotes. However, this:

extension: @string.Format("\"{0}\"", string.Join("|", new FileHelper().ValidFileExtensions)))

Results in the MVC engine rendering the quotes as " markup.

Can I get my file extensions wrapped in quotes?

Upvotes: 0

Views: 92

Answers (2)

komeil shahmoradi
komeil shahmoradi

Reputation: 321

Declare variable in Your view like this:

@{
   string validation = string.Format("\"{0}\"", string.Join("|", new FileHelper().ValidFileExtensions)));
 }

And use like this:

extension: @validation

Upvotes: 0

David
David

Reputation: 218828

The quotes are client-side, not server-side. Just put them directly in the client-side code like you would for any other string literal:

extension: '@string.Join("|", new FileHelper().ValidFileExtensions))'

Upvotes: 1

Related Questions