I. Preface
It is good to write a preface. Let's take a look at this.ArticleIt is a general content, and then soy sauce, passing by continues to pass by, but I believe there will always be some gains to stop.
I haven't written anything for a long time. I have been very busy recently. I don't seem to have any special content to write, and I have nothing to share with you. Recently, the front-end of a project used MVC and used the spark engine. It was very difficult to use it and did not dare to hide it. I would like to share it with you, but because of the fact that there is no Chinese spark information, therefore, this article can be considered as a translation, but the translation level is almost the same. If some experts have pointed out the shortcomings, it would be better.
ASP. net MVC currently has four main view engines: spark, nhaml, razor, and traditional aspx file templates. Razor is a new thing, the traditional aspx file templates have been widely used in MVC, and spark and nhaml seem to be not used much. It is likely that there is a lack of Chinese materials, which leads to a lack of understanding. I am searching for the keyword ASP. net MVC spark, Baidu and Google are both articles: Asp. net MVC's four view engines, the article just roughly writes the characteristics of each view, it is indeed a little bit of understanding.
This article is basically a translation of the spark official documentation. Its website is: http://sparkviewengine.com/documentation. if the network is not busy, please go over the wall!
2. Load spark into ASP. NET MVC
The spark engine is not managed by the controller. The simplest method is to use ASP. net mvc web applications.ProgramRegister sparkviewfactory in global application_start, for example:
Protected void application_start (Object sender, eventargs E)
{
Viewengines. Engines. Add (New sparkviewfactory ());
}
This is also the method for registering other non-default view engines.
Iii. Spark Configuration
1. configuration in Web. config
All Spark configurations are included in the <spark> tag, for example:
<! -- Add the spark configuration name -->
<Configsections>
<Section name = "spark" type = "spark. configuration. sparksectionhandler, spark"/>
</Configsections>
<! -- Spark configuration subject -->
<Spark>
<Compilation DEBUG = "True | false" defaultlanguage = "Default | CSHARP | VisualBasic">
<Assemblies>
<Add Assembly = "yourassemblyname"/>
<Add Assembly = "yourotherstrongassemblyname, version = 3.5.0.0, culture = neutral, publickeytoken = 31bf3856ad364e35"/>
</Assemblies>
</Compilation>
<Pages automaticencoding = "True | false" pagebasetype = "Your. nondefault. basesparkview" prefix = "{optional string}">
<Namespaces>
<Add namespace = "system"/>
<Add namespace = "system. Collections. Generic"/>
<Add namespace = "system. LINQ"/>
<Add namespace = "system. Web. MVC"/>
</Namespaces>
<Resources>
<Add match = "/content/CSS" location = "http://www.yourcdnprovider.com/youraccount/allstyles/css"/>
<Add match = "/content/JS" location = "http://www.yourcdnprovider.com/youraccount/appname/js"/>
</Resources>
</Pages>
</Spark>
It is best to use true for automatic decoding. This will encoding HTML for every operator using $ {expr! {Expr} will not be decoded
The resources area is used to control the shape like "~ /"Style links, such as: <SCRIPT src = "~ /Content/JS/Foo. js "/> will be parsed into a given location +"/Foo. js ", which is very meaningful for using static files or CDN.
2. You can also configure it in application_start, for example:
Protected void application_start (Object sender, eventargs E)
{
VaR settings = new sparksettings ()
. Setdebug (true)
. Setpagebasetype ("Your. nondefault. basesparkview ")
. Addassembly ("yourassembly ")
. Addnamespace ("system ")
. Addnamespace ("system. Collections. Generic ")
. Addnamespace ("system. LINQ ")
. Addnamespace ("system. Web. MVC ");
Viewengines. Engines. Add (New sparkviewfactory (settings ));
}
Iv. General syntax
1, including Code
you can use any helper method, including C # code, an object attribute or an expression that returns a non-null value, for example,
$ {"Hello World"}
$ {guid. newguid (). tostring ("N")}
code can be represented as special HTML tags or their attributes, such as "if", "else", and "Var ", $ {} is not required in the code area, such as:
beta is my favorite.
$ {name} is okay too I suppose.
however, if you want to output a common tag attribute, you must add the tag symbol, for example:
$ {currentproduct. name} edit
2. special characters in the code
You can use all C # code, but be careful to make sure that your business logic is written in your controller or other code.
Only a few pieces of code need special methods to avoid parsing errors, such as [[and] instead of <>. In addition, if double quotation marks are used in attributes, if spark syntax is used in the attribute, single quotation marks are required. If a single char constant is used, (char) 'X' is used instead of "X", for example:
<Viewdata products = "ilist [[products]"/>
<Var styles = "new [] {'even', 'odd'}"/>
3. Configure the spark prefix
By default, spark labels do not require other special tags. However, when spark is used to generate xml or XHTML, it is necessary to configure the spark prefix as follows:
<Spark>
<Pages prefix = "S"/>
</Spark>
Or
VaR settings = new sparksettings ()
. Setprefix ("S ");
When a prefix is configured, Each spark tag or attribute must start with a previous fix to be recognized by the spark engine. Spark's built-in tags such as macro:, content:, use: and section: you do not need to add a prefix, such:
<Div>
<S: viewdata user = "userinfo"/>
<P S: If = "user! = NULL ">$ {user. name} </P>
<S: loginform/>
</Div>
4, introduce xmlns namespaces to spark tags
This is not very easy to understand, directly on the example:
xmlns: S = "http://sparkviewengine.com/"
xmlns: fn = "http://sparkviewengine.com/macro/">
$ {favorite} is my favorite.
$ {name} is okay too I suppose.
$ {shownames ("Beta ")}
$ {shownames ("gamma") }< br>
5. Variables
1. Declare local variables
The "Var" label can be used to easily and quickly declare local variables. The default behavior will be to generate a local dynamic variable type with an initial value "Var", for example:
<Var styles = "new [] {'odd', 'even'}" I = "0"/>
Will generate the following:
VaR styles = new [] {"odd", "even "};
VaR I = 0;
The "Var" tag has a "type" attribute that specifies the type of the variable, for example:
<Var Foo = "null" bar = "null" type = "string"/>
Will generate the following:
String Foo = NULL;
String bar = NULL;
Finally, if the "Var" tag is not declared in a tag ending with "/>", the variable will have a scope and the scope will end with "</var>, variables cannot be assigned a value outside the scope, for example:
<Div>
<Var styles = "new [] {'even', 'odd'}" I = "0">
<P >$ {I} is $ {styles [I % 2]} </P>
</Var>
<Set I = "5"/> <! -- Compiler error-variable I is out of scope -->
</Div>
Will generate the following:
Output. Write ("<div> ");
{
VaR styles = new [] {"even", "odd "};
VaR I = 0;
Output. Write ("<p> ");
Output. Write (I );
Output. Write ("is ");
Output. Write (styles [I % 2]);
Output. Write ("</P> ");
}
Output. Write ("</div> ");
I = 5;
2. Declare global variables
local variables have their own scopes, while global variables can be declared in view, master, or partial template files. Their values can be used anywhere, for example:
$ {Title}
note that the value is enclosed by double quotation marks, there are also single quotation marks (it can be understood as double quotation marks because the HTML Tag attribute values must be included in double quotation marks while the string type is inside. Use single quotation marks to avoid repeated use of external double quotation marks)
the global variable will actually be executed by a field member in the View class. Therefore, a field member of object Title = "my default title" will be generated in the above example, this variable can be referenced by any method. Spark still provides a "type" attribute to declare the specific type to avoid using the object type. In addition, multiple variables can be declared in the same tag, for example:
3. Set the local and global variable values
$ {expr} and other syntaxes are only used for output values. To assign values to local or global variables, use the "set" label, for example:
$ {title }
set the title value in the view
4. View data
Viewdata can be used as an object dictionary, for example, $ {viewdata ["blah"]}. However, we recommend that you use a strong viewdata type to simplify the operation, for example:
<Viewdata
Caption = "string"
Products = "system. Collections. Generic. ilist [[MyApp. Models. Product]"/>
<Div>
<H3 >$ {caption}
<Div each = "Var product in products">
<H4 >$ {product. name} </H4>
<Div >$ {product. Description} </div>
</Div>
</Div>
The viewdata tag can be declared in the view or master file, and the results are the same, for example:
String Caption
{Get {return (string) viewdata ["caption"] ;}}
System. Collections. Generic. ilist <MyApp. Models. Product> Products
{Get {return (system. Collections. Generic. ilist <MyApp. Models. Product>) viewdata ["Products"] ;}}
In this case, [[and] must be used instead of <and>
5. Use the model of the determined type in view Data
In the view or master file, viewdata may have a model attribute.
<Viewdata model = "MyApp. Models. catalog"/>
<P> ($ {viewdata. model. catalogid}) $ {viewdata. model. name} </P>
The attribute of the model can be used together with the variable declaration in other viewdata. For example, a <viewdata Title = "string"/> is used in the master file, you can still use the model with a string field containing the title attribute in the view. <viewdata model = "typename"/>
<Viewdata Title = "string"/>
<Title >$ {html. encode (Title ?? "My sample MVC application")} </title>
This paragraph is hard to understand. We suggest you read the original English text.
Vi. Expressions
1. Simple C # expression
You can use $ {expr} or <% = expr %>
Example:
<Div>
<P> the time is $ {datetime. Now}. </P>
<P> the time is <% = datetime. Now %>. </P>
</Div>
2. nulls expression
When a simple C # expression is used, if the value is null, an error is returned. You can use $! {Expr} to avoid output errors, but the output is null.
<Div class = "shipto">
<P> $! {Currentinvoice. shipto. fullname} </P>
<P> $! {Currentinvoice. shipto. Address. City}, $! {Currentinvoice. shipto. Address. State} $! {Currentinvoice. shipto. Address. Zip} </P>
</Div>
If currentinvoice is null or shipto is null, the output is as follows:
<Div class = "shipto">
<P> </P>
<P>, </P>
</Div>
This idea is not very good, but it is always better than a garbled error page, so make sure your value of 100% is not blank
3. Use MVC helpers
You can use htmlhelper, urlhelper, and ajaxhelper.
<! -- Link to the sort action on the Current Controller -->
<P >$ {html. actionlink ("Click me", "sort")} </P>
<! -- Put out data in a way that's safe -->
<P >$ {html. encode (stuff)} </P>
4. Condition tags: If, test, and Else
Example:
Example 1:
<Var x = '5'/>
<If condition = 'X = 5'>
<P class = 'resultmessage'> some value is five </P>
</If>
Example 2:
<Viewdata user = 'userinfo'/>
<If condition = '! User. isloggedin () '>
<P> here's a login form </P>
</If>
<Else if = 'user. hasrole (roletype. Administrator) '>
<P> hello-you're an admin </P>
</Else>
<Else if = 'user. hasrole (roletype. Registered) '>
<P> hello-you're a registered user </P>
</Else>
<Else>
<P> I have no idea what type of person you are </P>
</Else>
Example 3:
You can use the <test if = ""> syntax to replace the <if condition = ""> syntax, <else if = ""/> and <else/> to replace the scattered labels.
<Viewdata user = 'userinfo'/>
<Test if = '! User. isloggedin () '>
<P> here's a login form </P>
<Else if = 'user. hasrole (roletype. Administrator) '/>
<P> hello-you're an admin </P>
<Else if = 'user. hasrole (roletype. Registered) '/>
<P> hello-you're a registered user </P>
<Else/>
<P> I have no idea what type of person you are </P>
</Test>
5. Use if and elseif to determine the attribute or Label display.
If and elseif can be used in any tag
Example 1:
<Var x = '5'/>
<P If = 'X = 5' class = 'resultmessage'> some value is five </P>
Example 2:
<Use namespace = 'sampleapp. models'/>
<Viewdata user = 'userinfo'/>
<P If = '! User. isloggedin () '> here's a login form </P>
<P elseif = 'user. hasrole (roletype. Administrator) '> hello-You' re an admin </P>
<P elseif = 'user. hasrole (roletype. Registered) '> hello-you're a registered user </P>
<Else>
<P> I have no idea what type of person you are </P>
</Else>
6. One judgment
you only need to call a resource once on the page, such as a CSS file or jquery. You can use once = "flagname" in the tag to specify, of course, you can use $ {expr} or other syntax to assign a value to flagname, in fact, this expression can be used anywhere in the spark file
This is not too clear
7. Conditional attribute output
Use? The {Boolean} expression can only be used in attribute values. For example:
<Ul>
<Li each = "Var product in products" class = "first? {Productisfirst} last? {Productislast} ">
$ {H (product. Name )}
</LI>
</Ul>
Will output
<Ul>
<Li class = "first"> alpha </LI>
<Li> beta </LI>
<Li> gamma </LI>
<Li class = "last"> Delta </LI>
</Ul>
Or
<Ul>
<Li class = "first last"> just one product </LI>
</Ul>
If the property value is null, the following result is displayed:
<Input type = "checkbox" name = "chkhello" Checked = "? {Ishellochecked} "> </input>
Will output
<Input type = "checkbox" name = "chkhello" Checked = ""> </input>
Or
<Input type = "checkbox" name = "chkhello"> </input>
8. Loop
A foreach loop contains the label for and each attributes. The each attribute value must contain the type, variable name, keyword "in", and loop body (collection), such:
<Viewdata posts = "ilist [[MyApp. Models. Post]"/>
<For each = "Var post in posts">
<P >$ {post. Title} </P>
</For>
Any loop has the index, Count, isfirst, and islast attributes. They are valid within the loop scope and are generated only when they are used, for example:
<Viewdata posts = "ilist [[MyApp. Models. Post]"/>
<Var styles = "new [] {'even', 'odd'}"/>
<For each = "Var post in posts">
<P class = "$ {styles [postindex % 2]}" >$ {postindex}. $ {post. Title} </P>
</For>
If the count or islast variable is used in the loop, spark will use the LINQ method of ienumerable <t> and obtain it using count, the old spark engine cyclically obtains the Count value. Therefore, when using count and islast, pay attention to performance issues.
Complex use of local variables and loops
<Viewdata currentproductid = "int"/>
<Var styles = "new [] {'even', 'odd'}" iscurrent = "false">
<For each = "Var product in products" iscurrent = "product. ID = currentproductid">
<P class = "highlighted? {Iscurrent }$ {styles [productindex % 2]} ">$ {html. encode (product. Name)} </P>
</For>
</Var>
9. Use loops in tag attributes
Example 1:
| name |
type |
| $ {user. name} |
$ {user. usertype } |
Example 2:
| name |
type |
| $ {userindex }) $ {user. name} |
$ {user. usertype } |
10. Use namespace
<Use namespace = "system. Collections. Generic"/>
<Use namespace = "system. Web. MVC"/>
<Viewdata names = "ilist [[String]"/>
Poor description
11. built-in code
Use the '#' symbol to declare the current behavior C # code, for example:
<Test if = "user. isloggedin ()">
<P> hello, $ {user. name}. </P>
<Else if = "user. hasvalidtrialsession ()"/>
<P> hello, valued future customer. </P>
<Else/>
<P> hello, er... you. </P>
# System. Diagnostic. Trace. writeline ("unexpected anon user .");
# If (system. Diagnostic. Debugger. isattached)
# System. Diagnostic. Debugger. Break ();
</Test>
Note that spark variables and C # variables are common!
12. shengminghong
When you need a helper method, if you need to input some parameters and return a string, <macro> can do this, <macro name = "foot"> is used for declaration, and $ {Foo ()} or <% = Foo () %> is used. For example:
<Viewdata errormessage = "string"/>
<Macro name = "showerror" caption = "string" message = "string">
<Div class = "message error">
<H3 >$ {H (Caption)}
<Div >$ {message} </div>
<% Logger. Warn (Caption); %> <! -- This is a Mr example. Asp.net MVC wocould use different logging -->
</Div>
</Macro>
<H2> place order </H2>
<Test if = "! String. isnullorempty (errormessage) ">
$ {Showerror ("failed to place order", errormessage )}
</Test>
Will generate the following:
String showerror (string caption, string message)
{
Using (outputscope (new system. Io. stringwriter ()))
{
Output. Write ("\ r \ n <Div class = \" message error \ "> \ r \ n Output. Write (H (Caption ));
Output. Write ("Output. Write (Message );
Output. Write ("</div> \ r \ n ");
Logger. Warn (Caption );
Output. Write ("</div> \ r \ n ");
Return output. tostring ();
}
}
//... And in the renderviewcontent Method
Output. Write ("\ r \ n <H2> place order </H2> \ r \ n ");
If (! String. isnullorempty (errormessage ))
{
Output. Write (showerror ("failed to place order", errormessage ));
} // If (! String. isnullorempty (errormessage ))
Output. Write ("\ r \ n <! -- Form here, field validation messages, etc. --> \ r \ n ");
Too many. I wrote this article today. I think it's good. Please recommend one.