Details and considerations for ASP. NET MVC Development Learning process

Source: Internet
Author: User

Tag: IDT exists field load avoids CPP MVC LOB int

1. The value of JS function in the DataGrid:

Columns

{
Field: ' TypeName ', title: ' Category name ', width:120, Sortable:true,
Formatter:function (value, row, index) {
var contentdetails = "<a href=" style= ' text-decoration:none; ' onclick= ' Showdetailsdialog ("+ Row.ID +"); re Turn false ' > ' + value + ' </a> ';
return contentdetails;
}
},

Note the value of the Click event above (row. ID or value) is generally an int type, and if the value passed is a string, you need to be careful to add the transfer character symbol. For example, the value of the class name should be the following code:

{
Field: ' TypeName ', title: ' Category name ', width:120, Sortable:true,
Formatter:function (value, row, index) {
var contentdetails = "<a href=" style= ' text-decoration:none; ' onclick= ' Showdetailsdialog (\ "+ value +" \ ") ; return false ' > ' + value + ' </a> ';
return contentdetails;
}
},

2. MVC @Html. DropDownList display Default value issues

View page code:

@Html. DropDownList ("Classpre", (selectlist) viewbag.jy_atype_classpre, "= = Please select upper class = =", new {@style = "width:60%; Height:32px "}) or

@Html. DropDownList ("Classpre", (selectlist) Viewbag.jy_atype_classpre, new {@style = "width:60%; Height:32px "})

Styles can also be removed

The code inside the controller:

Viewbag.jy_atype_classpre = new SelectList (newlist, "ID", "TypeName", model.) Classpre);

Note: the name of the control and the ViewBag (or ViewData) cannot have duplicate names. For example: Do not use Viewbag.classpre or viewbag.typename or viewbag.id such name, try to avoid such names.

3, using a recursive algorithm format display multilevel classification name

Effects such as:

list<jy_atype> lst = Bll.selectall ();
list<jy_atype> NewList = new list<jy_atype> ();
Bll. Getmylist (LST, ref newlist, 0, 1); Recursive formatting classification
Viewbag.jy_atype_classpre = new SelectList (newlist, "ID", "TypeName", model.) CLASSPRE);

///Recursive Method format classification
//</SUMMARY>
//<param name= List "> Data </param> for the list type that needs to be formatted,
//<param name=" NewList "> Data </param> for list type returned after formatting;
// <param name= "Step" > Step, first time execution is 0</param>
//<param name= "Perid" > This is the category ID of the previous class (that is, the parent ID of the current category) </param>
public void Getmylist (list<jy_atype> List, ref list<jy_atype> newlist, int step, int perid )
{
if (list. Count = = 0)
{
return;
}

String _step = "";
for (int i = 0; i < step; i++)
{
_step + = "";
}
_step + = "├";
foreach (Jy_atype atype in list)
{
if (atype. Classpre = = Perid)
{
int n = newlist.count;
Newlist.add (Atype);
Newlist[n]. TypeName = _step + atype. TypeName;
Newlist[n].id = atype.id;
Newlist[n]. Classorder = Atype. Classorder;
Newlist[n]. Classpre = Atype. Classpre;
Newlist[n]. IsSystem = Atype. IsSystem;
Newlist[n]. IMG = Atype. IMG;
int newstep = step + 1;
Getmylist (list, ref newlist, Newstep, Convert.ToInt32 (atype.id));
}
}
}

4, MVC using Baidu Rich Text Editor in the Edit view page news content initialized to empty problem:

<span style= "Display:none;" >
<input type= "hidden" id= "Content" class= "Easyui-textbox" style= "width:100%; height:32px; Display:none, "value=" @Model. Content ">
</span>

<script type= "Text/javascript" >

var URL = "/ueditor/"; Here you can configure the relative path or absolute path of the Ueditor directory on your site

var editor = new Baidu.editor.ui.Editor ({initialframeheight:280, initialframewidth:750});

Editor.render ("editor");

Editor.ready (function () {
Editor.setcontent ($ (' #Content '). Val ());
});

</script>

5. MVC data Annotations and validation references

Using System.ComponentModel.DataAnnotations;

C:\Program Files (x86) \reference Assemblies\microsoft\framework\. Netframework\v4.0\system.componentmodel.dataannotations.dll

6. An MVC reference was added to the project, but the compilation was unsuccessful, always prompting the system.web to not include the MVC name: Flagtype.selectlistitems

Final FIX: The project. Net Framework version is unified.

7. Set the page cache for asp:

If the page added: <%@ OutputCache duration= "" "varybyparam=" None "%>, may cause page pagination is not normal, try not to adopt page cache.

8, JQuery easyui page input box event JS:

<div class= "Editor-field" >
<input required= "true" id= "Pagecode" name= "Pagecode" value= "@Model. Pagecode" class= "Easyui-textbox" style= "width: 60%; height:32px "/>
@Html. validationmessagefor (model = model. Pagecode)
</div>

Js:

<script type= "Text/javascript" >
$ (function () {

$ ("Input", $ ("#PageCode"). Next ("span")). blur (function () {
Alert (This). Val ());
var code = $ (This). Val ();
$.post ("@Url. Action (" Ishavepagecode "," sys_rolepermission ")", {Pagecode:code}, function (data) {

if (data.tostring () = = "1") {
Alert ("already has the same module code");
}
});


});

});


</script>

9. Enable CSS and JS file bundle optimizations in ASP. NET MVC:

Use bundletable to bundle multiple CSS files and JS files to improve the speed of network loading and page resolution.
Turn bundle optimizations on and off by modifying the Enableoptimizations property of bundletable in the Global.asax.cs file.

protected void Application_Start(){ //other code has been removed for clarity //disable optimization System.Web.Optimization.BundleTable.EnableOptimizations = false;}


10、 ASP.NET MVC中有哪几种方式去修改默认的layout

(1)、修改根目录下的Views文件夹的 _ViewStart文件。_ViewStart为web application定义了默认layout页面。可以通过代码根据不同的Controller加载不同的layout。
controller =HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString(); string layout = ""; if (controller == "Admin") { layout = "~/Views/Shared/_AdminLayout.cshtml"; } else { layout = "~/Views/Shared/_Layout.cshtml"; } Layout = layout;}

(2), in the Views folder of a view directory to add a _viewstart file.

(3), modify layout at the top of the view page
@{ Layout = "~/Views/Shared/_AdminLayout.cshtml";}

(4), specify layout in ActionResult
public ActionResult Index(){ RegisterModel model = new RegisterModel(); //TO DO: return View("Index", "_AdminLayout", model);}

11. There are three ways to transfer a value from a controller to a view in ASP. (There is also an entity model pass value is not said):
ViewData, ViewBag and TempData. The session can be used to persist data in a single user session in ASP. NET WebForm.

ViewData

      • ViewData is a Dictionary object that inherits from a ViewDataDictionary class.
        public ViewDataDictionary ViewData { get; set; }
      • The ViewData is used to transfer values from the controller to the corresponding view.
      • The life cycle exists only in the current request.
      • If a redirect occurs, the value will be emptied.
      • Type conversions and null check are required to avoid exceptions when values are taken from ViewData.

ViewBag

      • ViewBag ViewBag is a dynamic property that is based on the characteristics of C # 4.0 dynamic language.
        public Object ViewBag { get;}
      • is a package for viewdata and is used to transfer values from the controller to the corresponding view.
      • The life cycle exists only in the current request.
      • If a redirect occurs, the value will be emptied.
      • A type conversion is not required to take a value from the ViewBag.

TempData

        • tempdata is an inherited tempdatadictionary class, stored in the session.
          public tempdatadictionary tempdata {get; set;}
        • tempdata is used for cross-page request transfer values.
        • tempdata The life cycle ends after being requested.
        • a type conversion and a null check are required to avoid exceptions when values are taken from TempData.
        • Details can refer to: TempData know how much,
          Session
        • asp.net MVC is a property in the controller, The session is the Httpsessionstatebase type.
          public httpsessionstatebase Session {get;}
        • session Save the data until the end of the user session (the default session expires at 20mins).
        • session is valid for all requests, not just a single jump.

12. Data annotations (data annotations)

The Data Annotation attribute is located System.ComponentModel.DataAnnotations under the namespace and is suitable for ASP. NET projects (such as ASP. NET Web Application & website, ASP. Web Forms), and also for ORM model.
Data annotations helps us to validate the model class or attribute definition rules and to display appropriate hints to end customers.
Data Annotation Validation Features:

      • DataType-Specifying a data type for a property
      • DisplayName-Specify a display name for the property
      • DisplayFormat-Specify the display format for the property
      • Required-Restricted attribute is required
      • Reqularexpression-Verifies whether the value of the property meets the requirements with a regular expression
      • Range-Limit the value of a property in a range
      • Stringlength-Specifies the minimum and maximum length of a String type property
      • MaxLength-Specifies the maximum length of a String type property
      • Bind-When you add a parameter or form data to the model property, the specified field is added to or excluded
      • Scaffoldcolumn-hides the specified field of the form editing interface

How to register area in asp:

Before using area, make sure you are registered in the Application_Start method of Global.asax.

protected void Application_Start(){ //Register all application Areas AreaRegistration.RegisterAllAreas();}

It is important to remember that the area must be registered at the very beginning so that the registered settings, filters and routes
can be applied to area.

14, and ASP. NET, MVC Forms authentication occurs after IIS authentication is complete. Can be configured in the forms node of the Web. config file in an ASP. NET MVC application.

The default form authentication configuration is as follows:

<system.web><authentication mode= "Forms" ><forms loginurl= "Login.aspx" protection=" all "timeout=  "name=". Aspxauth "path="/" Requiressl= "false" slidingexpiration=  "true" defaulturl= " Default.aspx "cookieless=" usedeviceprofile "enablecrossappredirects=" false "/></authentication></ System.web> 

15,
how ASP. NET MVC allows you to enter HTML tags:

ASP. NET MVC does not allow users to submit HTML by default to avoid cross Site Scripting (CSS) attacks.
ValidateInputAttributes can enable or disable input validation at the action level or controller level.

[ValidateInput(false)]public class HomeController : Controller{ public ActionResult AddArticle() { return View(); }}

ValidateInputAttributes allow HTML tag input for all properties, but this is not secure. If you just want to allow HTML input for a partial property, you can add attributes to the attribute AllowHtml .

public class BlogModel{ [Required] [Display(Name = "Title")] public string Title { get; set; } [AllowHtml] [Required] [Display(Name = "Description")] public string Description { get; set; }}

16. Set the cache in MVC

Action Cache, 10 seconds
[OutputCache (Duration = 10)]
Get:home
Public ActionResult Index ()
{
Viewbag.currenttime = DateTime.Now;
return View ();
}

Public ActionResult Index2 ()
{
Viewbag.currenttime = DateTime.Now;
return View ();
}

Using configuration files for cache configuration

In the MVC Web. config file, you can configure the cache in a related configuration.

In the system.web node, add the caching child node, and then the following:

<outputCacheSettings>        <outputCacheProfiles>          <add name= "Testconfigcache" duration= "10"/ >        </outputCacheProfiles> </outputCacheSettings>

Once configured, our control cache or action cache can be written like this:

[OutputCache (cacheprofile= "Testconfigcache")]        Get:home public        ActionResult Index ()        {            viewbag.currenttime = DateTime.Now;            return View ();        }

Details and considerations for ASP. NET MVC Development Learning process

Related Article

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.