Asp.net MVC (4)

Source: Internet
Author: User

I have a problem similar to the following in Asp.net MVC (3): There is a partial view control that is used in the home view. How do I obtain the key and value ?? It is how to pass values to the view in the partial view control.

I mentioned the application of viewdata at the time, but viewdata is limited to the current action. Now with tempdata, everything is fixed.

Solution:Modify the action for generating the message: assign a value to tempdata.

[Acceptverbs (httpverbs. Post)]
Public Actionresult create (guestbookinfo Model)
{
Try
{
Inter. Add (model );
VaR Models = Inter. findallinfo ();
Tempdata [ " Tempdata " ] =   " Created successfully " ;
Return Redirecttoaction ( " Index " );
}
Catch (Exception ex)
{
Modelstate. addmodelerror ( " Ex " , Ex );
Return View (model );

}
}

Then, in the index view, you can easily access the following values: <% = tempdata ["tempdata"] %>. Interestingly, when tempdata ["tempdata"] is not assigned a value, this statement does not cause errors.

Let's take a look at why data can be transferred between controllers through tempdata. In traditional Asp.net, we often use session or cookie to transmit values, because tempdata does not pass values through webpage parameters, so it must be the reason for storing data somewhere.

First, view the source code of the controller class.It contains an important method: The tempdata. Load Method of the base class is called before this aspect starts.

Protected   Override Void Executecore ()
{
Base . Tempdata. Load ( Base . Controllercontext, This . Tempdataprovider );
Try
{
String Requiredstring =   This . Routedata. getrequiredstring ( " Action " );
If ( ! This . Actioninvoker. invokeaction ( Base . Controllercontext, requiredstring ))
{
This . Handleunknownaction (requiredstring );
}
}
Finally
{
Base . Tempdata. Save ( Base . Controllercontext, This . Tempdataprovider );
}
}


Second: tempdata. Load Method:It can be seen that the itempdataprovider interface is used in the end.

Public   Void Load (controllercontext, itempdataprovider tempdataprovider)
{
Idictionary < String , Object > Dictionary = Tempdataprovider. loadtempdata (controllercontext );
This . _ DATA = (Dictionary ! =   Null ) ?   New Dictionary < String , Object > (Dictionary,

Stringcomparer. ordinalignorecase ): New Dictionary < String , Object > (Stringcomparer. ordinalignorecase );
This . _ Initialkeys =   New Hashset < String > ( This . _ Data. Keys );
This . _ Modifiedkeys. Clear ();
}


Third: itempdataprovider: We canCodeThe interface is obtained as follows:

Public Itempdataprovider tempdataprovider
{
Get
{
If ( This . _ Tempdataprovider =   Null )
{
This . _ Tempdataprovider =   New Sessionstatetempdataprovider ();
}
Return   This . _ Tempdataprovider;
}
Set
{
This . _ Tempdataprovider = Value;
}
}

Fourth: sessionstatetempdataproviderWe can guess from this name that the data should be saved in session mode. It mainly includes two methods for loading data and saving data.

Public   Virtual Idictionary < String , Object > Loadtempdata (controllercontext)
{
Httpcontextbase httpcontext = Controllercontext. httpcontext;
If (Httpcontext. Session =   Null )
{
Throw   New Invalidoperationexception (mvcresources. sessionstatetempdataprovider_sessionstatedisabled );
}
Dictionary < String , Object > Dictionary = Httpcontext. session [ " _ Controllertempdata " ] As Dictionary < String ,

Object > ;
If (Dictionary ! =   Null )
{
Httpcontext. session. Remove ( " _ Controllertempdata " );
Return Dictionary;
}
Return   New Dictionary < String , Object > (Stringcomparer. ordinalignorecase );
}

Public   Virtual   Void Savetempdata (controllercontext, idictionary < String , Object > Values)
{
Httpcontextbase httpcontext = Controllercontext. httpcontext;
If (Httpcontext. Session =   Null )
{
Throw   New Invalidoperationexception (mvcresources. sessionstatetempdataprovider_sessionstatedisabled );
}
Httpcontext. session [ " _ Controllertempdata " ] = Values;
}


Summary: Although tempdata uses sessions to store data, the cost for the server is low, because the Code shows that tempdata will be eliminated once used up. When we see this, we can think about whether we can define a tempdataprovider. Of course we can. Here I create an example without any functional changes, which can be modified as needed:

1: Create mytempdataproviderTo Inherit itempdataprovider and implement loadtempdata and savetempdata.

2: contact the Controller with mytempdataprovider.You can choose to extend the default controller Factory (defaultcontrollerfactory) and rewrite the icontroller createcontroller method:

Public   Override Icontroller createcontroller (requestcontext, String Controllername)
{
Controller =   Base . Createcontroller (requestcontext, controllername) As Controller;
If ( Null   ! = Controller)
{
Controller. tempdataprovider =   New Mytempdataprovider ();
}
Return Controller;

}


3: register our custom mycontrollerfactory, which is the last step.

Protected   Void Application_start ()
{
Controllerbuilder. Current. defaultnamespaces. Add ( " Guestbook. MVC. Controller " );
Modelbinders. binders. Add ( Typeof (Guestbookinfo ), New Guestbookbinder ());
Controllerbuilder. Current. setcontrollerfactory ( Typeof (Mycontrollerfactory ));
Registerroutes (routetable. routes );
}

Summary:By understanding the implementation mechanism and lifecycle of tempdata, it is not difficult for us to implement my previous difficulties.

Note: Reference: http://www.cnblogs.com/tristanguo/archive/2009/04/12/1433462.html
 

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.