Some methods of view and controller of MVC in net

Source: Internet
Author: User
Tags actionlink

1:viewdata Value-Transfer method
The ViewData life cycle is the same as view, only valid for the current view.
viewdata["ZD"] = DFDFD
2:tempdata Value-Transfer method
Can be passed across action
TempData data can only be passed once by the controller, and each element can be accessed at most once,

For example, one usage is to throw an exception. Jump to the error page
Public ActionResult Index3 ()
{
tempdata["Tempindex"] = "something went wrong!";
Response.Redirect ("/home/error");
return View ();
}
3:querystring Pass Value
1) You can also use new{} to add querystring to the action of the form
2) Get values in Controler using request.querystring["word"
For example:
<li>
<%= Html.ActionLink ("Browse", "Browse", "User", new {word = "word1"}})%></li>

Controler page:
Public ActionResult Browse (string word)
{
viewdata["word"] = request.querystring["word"];
viewdata["word2"] = Word;
return View ();
}
4:post Pass Value
Example: direct use of mehod=post
<%@ page language= "C #" inherits= "System.Web.Mvc.ViewPage"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<body>
<div>
<form action= "/user/addrelease" method= "POST" >
<ul>
<li> username 1:<input type= "text" value= "" Name= "UserName2"/></li>
<li> password 1:: <input type= "text" value= "" Name= "Password2"/></li>
</ul>
<input type= "Submit" value= "Add"/>
</form>
</body>
For example 2: You can also use the Htmlhelper.post method
<%@ page language= "C #" inherits= "System.Web.Mvc.ViewPage"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<body>
<div>
<% html.beginform ("Addrelease", "User", FormMethod.Post); %>
<ul>
<li> User name: <%= html.textbox ("UserName")%></li>
<li> Password: <%= html.textbox ("Password")%></li>
</ul>
<% Html.endform (); %>
<input type= "Submit" value= "Add"/>
</body>
Html.BeginForm
Html.endform
Html.textbox

An engineering structure
4 assemblies
MICROSOFT.WEB.MVC--some available, indeterminate packages
SYSTEM.WEB.MVC--Main Library
The following two are included in the 3.5 NET Framework
System.Web.Abstractions--request,respose and other 5 large objects, caches, those used for ASP. NET Webfrom, this use decorator mode to make the past use of the class, and MVC used under the class like compatibility.
System.Web.Routing--
With a reference to 3.5
System.Web.Extensions--ajax Controls
File
App_Data database
Content styles, pictures, JS, etc.
Controllers controller, can change name, default value
Models model
Views View
Two basic workflow
Http://localhost:23797/home/index
Home is the controller
Index is the action
HomeController---Index ()
Method return View (); This method will default to access the Home->index.aspx file under the View folder
Method return View ("about"); Visit the page we specified
Changed the code to regenerate it before it works
Three-MVC architecture
Page Request-->controller->models (ORM)-Database
|
Page <--views
Four viewdata values, this page view pass
The Controller-to-views passes the value between ViewData.
Controller Write viewdata["ZD"] = "welcome you!" ";
Call <%= viewdata["ZD" in view)%>

Alternatively, it can be a complex type
list<string> SL = new list<string> ();
Sl. ADD ("heavy Pawnage");
Sl. Add ("Ice Power");
viewdata["ZD"] = SL;
Called In view
<% foreach (String str in viewdata["ZD"] as list<string>) {%>
<%= Str%>
<%}%>
For ASPX pages, modifications can be made without compiling the build.
Five other way of tempdata, can be passed across the page action
tempdata["ddd"] = "haha";
Response.Redirect ("/home/about");
Page about in
<%= tempdata["ddd"]%>
Keep only one value at a time.

Use: For example, the program to run to a certain place, reported error thrown exception, to an exception handling page, the error message passed, specialized processing.
The other means of transmission of the six viewdata, the transmission of classes
Define a class
public class User
{
public string Name {get;set;}
public int ID {get;set;}
}
Instantiating in a controller
User user = new user ();
User.ID = 1;
User. Name = "Ann";

viewdata["User" = user;

In the View
<%= (viewdata["user"] as user). Name%>
There is also a more convenient way to:
Put the object in return View (user); Pass it Out
Page view
First modify the Page class inheritance
Like what:
public partial class Index:viewpage
-
public partial class Index:viewpage<user>
And then on the page
<%= ViewData.Model.Name%>

Only one reference type can be passed.
Passes an object to the page with a generic type.
Seven new page
1. Create a new controller
The default action is index
Public ActionResult Index ()
{
return View ();
}
2. Create a new view
With the same name as the controller just.
Eight redirects, Redirect
Response.Redirect ("/user/edit");
The Webfrom version usually jumps or supports
New return MVC mode jump
Return Redirect ("/user/edit");//New Jump
Return redirecttoaction ("edit");
Different action jump with controller
Return redirecttoaction ("index", "edit");
Different controller jumps
Nine URL Routing routing
Home/index
Ability to locate the-->home controller-->index Action
In the Golab.cs
Eight filter filters
Encoding and decoding data compression Service Setup protocol and so on, you can do it here.
Executes after the action has occurred
Execute after display before view display

Create a new class named Add Parameter Validation filter (Paramfiter)
Filter to inherit the base class of the filter System.Web.Mvc.ActionFilterAttribute

overriding method
protected override void OnActionExecuted (Actionexecutiongcontext filtercontext)
{
After action runs
}
protected override void OnActionExecuting (ActionExecutingContext filtercontext)
{
Before action runs
if (filtercontext.httpcontext.request.querystring["k"]! = "Goo")
{
throw new Exception ("This has an error");
}
}
protected override void Onresultexecuted (ResultExecutedContext filtercontext)
{
After the view display
}
protected override void Onresultexecuting (ResultExecutingContext filtercontext)
{
Before the view display
}
How to use filter filters
Add the class above the controller
[Paramfilter]
public class Homecontroler:controler
This filter will be used throughout the controller.
can also be placed on an action in the controller
[Paramfilter]
Public ActionResult Index ()
Http://localhsot:23797/?k=go will have access to the
Nine Helper First Experience
HtmlHelper used for the original server control, when displaying data to borrow helper
Urlhelper URLs have uncertainties due to the presence of URL routes
/home/index
/home/index.ashx
If the connection is written dead, it is necessary to replace the whole, with urlhelper can be avoided.

In addition, Helper can only be used on the view page, do not use the controller, this is not an absolute rule.
HtmlHelper can only be called on the View page with HTML.
Urlhelper just use the URL in the view page
Hypertext links
<%= Html.ActionLink ("Home", "index", "Home")%>
HtmlHelper can display all of the form elements, including the form that is used to display
<%= Html.textbox ("category")%>
HtmlHelper also has a special method for the output coding function
<%= Html.encode ()%>

Urlhelper is only used to display URLs.
<%= url.action ("index", "Home")%> display
<%= url.content ("//dd")%> the site path into a URL display

Ten-QueryString method of transmitting value
Url?key1=value&key2=value2
The time to get it is to use
request.querystring["Key1"]

In the controller,
viewdate["V"] = request.querystring["word"];
In the View
<%= viewdata["W"]%>
In the invocation page of the value of the transfer
<%= html.actionlink ("Editing page", "Edit", "user", new {word = "Zhongdian"},new {@class = "x"})%>
The last attribute is the extended a label, which gives it a style.
Because class is a keyword, you can either avoid the class (C caps) or escape with the @ leader.
Generated HTML page code
<a href= "/user/edit?word=zhongdian" class= "x" > Edit page </a>
There is an easier way to do this:
Rewrite in the Controllers
Public ActionResult Edit (string word)
As arguments to action
11 Form Submission Post
<form> because the URL submitted is also a factor of uncertainty, it is generated with helper.
Create a form
<% using (Html.form ("User", "edit", FormMethod.Post)) {%>
username:<%= Html.textbox ("username")%>
<br/>
password:<%= Html.password ("password")%>
<br/>
<%= Html.submitbutton ("", "submit")%>
<%}%>
The value of the element in the controller that accepts the form form
String un = request.form["Username"];
string PS = request.form["Username"];
viewdata["W"] = un + PS;
In the Page view
<%= viewdata["W"]%>
12 better way to pass the value, Updatemodel
Updatemodel is actually a method under the controller set, which stores the corresponding values of post and get submitted to an object.
Updatemodel ();
Defining classes
public class User
{
public string Name {get;set;}
public string Password{get;set;}
}
How to write in the method in the controller
User U = new user (); Model
Updatemodel (U,request.form.allkeys);//get can also
String un = u.name;
string ps = U.password;
viewdata["W"] = un + PS;
In the Page view
<%= viewdata["W"]%>
13 single-Select Check update
Radio Box
<%= Html.radiobutton ("N1", "man", false)%> sex
List of radio boxes
<%= Foreash (String s in
Html.radiobuttonlist ("Ah", new[]{"music", "Calligraphy"})
)
{%>
<%= s%>
<%}%>
check box
<%= Html.checkbox ("C1")%> check
How to accept a pass-through value in a controller
Viewdata["show"] = request.form["N1"]; Modify N1 to AH to test the display list
In the Page view
<%= viewdata["Show"]%>
If the value of the check box is multiple, and name is the same, you can receive its value with a string of data.

14 Form Validation
<form action= "" method= "POST" >
<%= Html.validatiesmessage ("U")%>
<fieldset>
<legend> Submit Users </legend>
<p><label> User name </label>
<%= Html.textbox ("U.username")%>
</p>
<p><label> Password </label>
<%= Html.textbox ("U.password")%>
</p>
<input type= "Submit"/>
</fieldset>
</form>
The code behind the controller
Httpverbs.post
Public ActionResult Index (U as User)
{
if (u.username! = "Heavy Pawnage")
ViewData.ModelState.AddModelError ("U", "User name error");
if (U.password! = "123456")
ViewData.ModelState.AddModelError ("U", "Wrong password");
return View ();
}

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.