Analysis and Solution to the conflict between HTML attribute names and keywords in MVC View

Source: Internet
Author: User

In the MVC view, {} can be used to define the attributes of an element.
However, the class attribute name in HTML conflicts with the class in C #. Therefore, you cannot use the class attribute when using it.

The solution is to add a @ symbol before the class. For example, if the class set for the element is item, you can write: {@ class = "item "}

<%: Html.TextBoxFor(model => model.Postcode, new { @class="postcode" }) %>

You can use the prefix "@" to use keywords as identifiers, which is useful when creating interfaces with other programming languages. The character @ is not an actual part of the identifier. Therefore, this identifier may be considered as a normal identifier without a prefix in other languages. The identifier with the @ prefix is calledVerbatim identifier(Verbatim identifier ). Allow @ prefixes to be used for non-Keyword identifiers, but (in the sense of code writing style) it is strongly recommended not to do so.

Example:

class @class{    public static void @static(bool @bool) {        if (@bool)            System.Console.WriteLine("true");          else            System.Console.WriteLine("false");    }}class Class1{    static void M() {        cl\u0061ss.st\u0061tic(true);    }}

Define a class named "class", which has a static method named "static". This method carries a parameter named "bool. Note that because Unicode escape characters are not allowed in keywords, the mark "Cl \ u0061ss" is an identifier, which is the same as the "@ Class" identifier.


In MVC, in addition to @, the problem can also be solved in this way.

<%: Html.TextBoxFor(model => model.Postcode, new Dictionary<string, object> { { "class", "postcode" } }) %>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.