ASP. NET MVC 3 entry-level common settings, tips, and errors

Source: Internet
Author: User
Tags type null

1. How to remove default validation for ASP 3

This default validation is set in the Web. config configuration file.
<add key= "clientvalidationenabled" value= "true"/> set to false on the line,
This is the default validation for all the model, and then you can add your own validation to the model, so which properties need to be verified and what you don't need to see yourself.

Example code:

Publicclass Movie
{
Publicint ID {get; set;}

[Required (errormessage= "must enter title")]
Publicstring Title {get; set;}

[Required (errormessage= "must enter release date")]
Public DateTime releasedate {get; set;}

[Required (errormessage= "must be developed type")]
Publicstring Genre {get; set;}

[Required (errormessage= "must enter Fare")]
[Range (1,100,errormessage= fare must be between 1 and $100 ")]
Publicdecimal price {get; set;}

[Stringlength (5,errormessage= "up to 5 characters allowed")]
Publicstring Rating {get; set;}
Publicstring Description {get; set;}
}

2. How to create HTML tags in the view of ASP. NET MVC 3 (compile the characters with tags into the corresponding tags in the view)

in the view in ASP. NET MVC 3, the string output is defaulted to the original string, and if you need to compile the label characters in the string into the corresponding label

You need to create a label at the time of the output: @MvcHtmlString. Create (viewbag.regionhtml); Viewbag.regionhtml is a string containing a label

3, ASP 3 Error: MVC 3 property cannot be set to "null" value. This property must be set to a non-null value of type "Int32".

This is because there are null values in the fields in the tables in the database (for example: Int,double,datetime, etc.)

It is only necessary to get rid of NULL in the value of the field of the corresponding numeric type in the database, for example, to change the number type null value to 0, the character type null value to the space, the date type null value to the date

4, database tables need to add s

There is a strange phenomenon in ASP. 3, many times after using Efcodefirst, the tables in the database need to add s, such as the original database table product

Now to become products, or many times will be error: Object name ' dbo. Products ' Invalid

5. How to use radio buttons in ASP 3 RadioButton

This is easier, both ways @Html. RadioButton or @Html. radiobuttonfor

1, @Html. RadioButton ("Sex", true) male 2, @Html. Radiobuttonfor (Model=>model. Sex,true) Male
@Html. RadioButton ("Sex", false) female @Html radiobuttonfor (Model=>model. Sex,false) Female

The sex here is the entity attribute, the data type is the bool type, it automatically matches the value of the database, the same selected

6. How to refer to JS files in ASP. 3

<script src= "@Url. Content (" ~/scripts/calendar4.js ")" Type= "Text/javascript" ></script>

The Calendar4.js file here is placed directly in the auto-generated Scripts folder of the website.

7. asp. 3 text box Custom Click event OnClick Event

There are two ways of

1, directly write HTML tags, as usual <input type= "text" id= "Birthday" name= "Birthday" onclick= "mycalendar.setdate (This)" value= "@ Model.birthday "/>

2. Write: @Html. TextBox ("Birthday", Model.birthday, new {onclick = "mycalendar.setdate (This)", style= "width:500px;"})

Data interaction on 1 and 2 is no big difference, but if you write validation, 1 is not referencing the wrong style, and 2 automatically correlates the error style.

8. ASP. NET MVC 3 using the drop-down list DropDownList

First, a selectlist control needs to be placed in the context (ViewData) in the controller.

The controller code is as follows:

Private Crmdbcontext db = new Crmdbcontext ();
var list = db. Partments.tolist ();
viewdata["PARTMENTDDL"] = new SelectList (list, "Id", "PartName", employee. Partmentid);

In the View :

1、 @Html.DropDownList("PartmentID", (SelectList)ViewData["partmentDDL"], "--this one--")2、 @Html.DropDownListFor(model => model.PartmentID, (SelectList)ViewData["partmentDDL"], "--this one--")

The Partmentid here is an entity attribute, which is automatically selected if there is a Partmentid value in SelectList in ViewData. "--this one--" adds an option to the drop-down list and fills null if you do not need to add it

9.ASP. NET MVC 3 with the key "XXX" of the ViewData item belongs to the type "System.Int32", but it must belong to the type "ienumerable<selectlistitem>".

Some people on the internet say yes: the main reason for the error is that the original drop-down list (from here) is not known at the place of submission. The solution is to repeatedly build the DropDownList code in the handle in the controller, such as

Public ActionResult Create ()
{
var actionlist = db. Actions.tolist ();
viewdata["ACTIONDDL"] = new SelectList (actionlist, "Id", "getmoactname");
var popedomlist = db. Popedoms.tolist ();
viewdata["PEPEDOMDDL"] = new SelectList (popedomlist, "Id", "property");
return View ();
}

//
POST:/actionpopedoms/create

[HttpPost]
Public ActionResult Create (actionpopedoms actionpopedoms)
{
var actionlist = db. Actions.tolist ();
viewdata["ACTIONDDL"] = new SelectList (actionlist, "Id", "getmoactname");
var popedomlist = db. Popedoms.tolist ();
viewdata["PEPEDOMDDL"] = new SelectList (popedomlist, "Id", "property");

if (modelstate.isvalid)
{
Db. Actinpopedoms.add (actionpopedoms);
Db. SaveChanges ();
Return redirecttoaction ("Index");
}
Return View (actionpopedoms);
}

Attention to these two methods, the first action method is to show the new page, that is, you click on the new feature in other places, through this method in the view, this view is a new page, in this method built two drop-down list, when we click the corresponding button to determine the new, The request is the second action method, the method passed in is an entity object (here is why an entity object is not specified), where the method is to execute the relevant new functions, where the new success will go to the action method index method, If the new failure goes to the current page (where the Code return view (actionpopedoms) is the new page), the problem is here, if the second method does not rebuild the drop-down list of code, then return to the current page, The page does not recognize the drop-down list that was built in the first action method, so the final error on the page is that the ViewData item with the key "XXX" is of type "System.Int32", but it must belong to the type "ienumerable< Selectlistitem> ". So just make sure the action in the second action method doesn't get an error. If you need to see the error message, you can try it and return to view (Error message)

10. How to import namespaces in the Razor view page of ASP. NET MVC 3

@usingMyNamespace

11.How to get the requested URL path in ASP. NET MVC 3 

stringurl = "";//url全部分url = HttpContext.Current.Request.Url.ToString();

12, ASP 3 TempData, ViewData, viewbag three differences

TempData ViewData ViewBag can be used to save data, the difference between them is as follows: TempData is saved in the session, and the controller gets tempdata from the session each time it executes the request. After the session is cleared, the TempData data is obtained, although it is saved in the internal Dictionary object, but each entry in its collection is accessed once and removed from the dictionary table. Specific code level, The TempData acquisition process is the Sessionstatetempdataprovider.loadtempdata method to read data from the ControllerContext session, and then clear the session, so tempdata can only cross control Ler Pass once. The ViewData life cycle and view are the same, only valid for the current view. ViewBag and ViewData have the same life cycle, but the former view is valid, except that the type of viewbag is no longer the key-value pair structure of the dictionary, but dynamic type, which is the new part of MVC3. -------From address

13. Use the radio button in ASP. RadioButton 3

Here for emergency purposes, we will introduce only one usage code as follows

<div class= "Editor-field" >
@Html. RadioButton ("Sex", Model.sex, Model.sex)
Man
@Html. RadioButton ("Sex",! Model.sex,! Model.sex)
Woman
@Html. validationmessagefor (model = model. SEX)
</div>

14. Get Page label information in ASP. NET MVC 3 controller

This is mainly through the form form to get the data submitted by the page

View Code:

@using (Html.BeginForm ()) {    @Html. ValidationSummary (True)    <fieldset>        <legend>album</ Legend>        @Html. hiddenfor (model = model. albumID)        <div class= "Editor-label" >            @Html. labelfor (model = model. Genreid)        </div>        <div class= "Editor-field" >            @Html. DropDownList ("Genreid", String. Empty)            @Html. validationmessagefor (model = model. Genreid)        </div>    </fieldset>}

Controller code:

Album. albumID =convert.toint32 (request.form["albumID"]);

ASP. NET MVC 3 entry-level common settings, tips, and errors

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.