OutputCache for partialView not working? - asp.net-mvc-3

Hi,
I have a ASP.NET MVC 3 website where I have created a action that returns a partial view. This view have the following :
<%# OutputCache Duration="10000" VaryByParam="none" %>
And to render this from my main view I use this :
<% Html.RenderAction("ImageWall", "Image"); %>
The problem is that it is not caching at all? When setting a breakpoint I can see that the expensive drawing is running everytime?

For this, Use Action Attribute
<OutputCache(Duration:=10000, VaryByParam:="any")>
Function ImageWall() As PartialViewResult
Return PartialView()
End Function
For Vb.Net sample, sorry

Related

Updating result from ajax calls in partial views in asp.net mvc2

I have a ASP.Net MVC 2 partial view like the one below,
FORM 1:
<div id="d1">
<% using (Ajax.BeginForm("ManageSources", "Sources",
saveAjaxOptions))
{ %>
... all this form's html markup goes here
<div id="src_Parameters"></div>
<% } %>
</div>
Form 2
<% using (Ajax.BeginForm("FetchParameters", "Sources",
fetchAjaxOptions))
{ %>
hidden fields to send values to the action method go here
.. button to post this form
<% } %>
Now, in the fetchAjaxOptions, i have given the target div to be src_Parameters, which resides inside the form1, when i post the second form, i am being returned a partial view as the only view page, instead of populating the results in the src_Parameters div.
How do i accomplish this. Actually the results of the FetchParameters ajax call should be able to be posted for the ManageSources ajax call.
Where is the problem or will nesting the forms workout since this is using ajax forms.. Kindly suggest me the right procedure to do this task.
You haven't posted your server side code, but I suspect you have forgotten to have set the return type to be a partial view.
public PartialViewResult FetchParameters()
{
//do some stuff
return PartialView(“_ViewName”, viewModel)
}
It could also be that you fotgot to add a reference to the Microsoft Ajax
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>

MVC3 - Error rendering partial view

why does this error occur.. The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments...when I am trying to put a partial view in a div like
<div>#Html.RenderPartial("_pagePartial");</div>
thanks for your help.
Because the correct syntax is this (notice the { }s):
<div>#{Html.RenderPartial("_pagePartial");}</div>
or if you prefer:
<div>#Html.Partial("_pagePartial")</div>
The reason for this is that contrary to the Partial extension method RenderPartial doesn't return anything. It directly writes to the output stream. Contrast this with the WebForm equivalents:
<% Html.RenderPartial("_pagePartial"); %>
<%= Html.Partial("_pagePartial") %>

Using Page.User.Identity.Name in MVC3

In MVC2 I have used Page.User.Identity.Name using the <%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
How can I use the same in MVC3?
You can always do something like:
#Html.ViewContext.HttpContext.User.Identity.Name
but don't.
Normally a view shouldn't try to fetch such information. It is there to display whatever information is passed by the controller. It should be strongly typed to a model class which is passed by a controller action.
So in the controller action rendering this view:
[Authorize]
public ActionResult Index()
{
var model = new MyViewModel
{
Username = User.Identity.Name
}
return View(model);
}
Now inside the view feel free to use this information:
#Model.Username
MVC 2
<%: this.Page.User.Identity.Name %>
MVC 3
#this.User.Identity.Name
I had the same problem. I used this tutorial to solve this issue.
In short, in your view, put this code:
#Context.User.Identity.Name
Just make sure that the project is set to authenticate with windows.

MVC Transfer Data Between Views

I just started to learn MVC and am trying to understand how it works.
I don't want to send users to different views for all edit, insert and list operations.
In my sample application a View contains a list of items and below the list there is a form (for inserting new items) with action "{Controller}/Create" but there is no Create View.
When a user inserts a new item it posts to the Create action with httpverb post and creates the item and returns back to the List action with RedirectToAction method.
But I can not show any message(error, information etc) to the user in this style because I can not pass data between Create action and List action. How can I do that?
You need to use Post Redirect Get PRG pattern.
Please read this Use PRG Pattern for Data Modification section in this blog post by Kazi Manzur Rashid.
http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx
This approach uses TempData to maintain ModelState data between redirects.
[HttpPost, ValidateAntiForgeryToken, ExportModelStateToTempData]
public ActionResult Create(FormCollection form)
{
Product p = new Product();
if (TryUpdateModel<IProductModel>(p))
{
productRepository.CreateProduct( p );
}
else
{
// add additional validation messages as needed
ModelState.AddModelError("_generic", "Error Msg");
}
return RedirectToAction("Index");
}
And here is your Index action method.
[ImportModelStateFromTempData]
public ActionResult Index()
{
IList<Product> products = productRepository.GetAll();
return View("Index", products);
}
And here is your Index view.
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IList<Product>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Products</h2>
<% foreach (var p in Model) { %>
<div><%= Html.Encode( p.ProductName ) %></div>
<% } %>
<%= Html.ValidationSummary("Please correct the errors", new { id = "valSumCreateForm" }) %>
<% using (Html.BeginForm("Create", "Product")) { %>
Product Name: <%= Html.TextBox("ProductName") %>
<%= Html.AntiForgeryToken() %>
<% ViewContext.FormContext.ValidationSummaryId = "valSumCreateForm"; %>
<% } %>
</asp:Content>
The ImportModelStateFromTempData
and ExportModelStateToTempData
attributes helps transfer model
state errors between redirects. This
<% ViewContext.FormContext.ValidationSummaryId = "valSumCreateForm"; %> associates the MVC Form with its corresponding Validation Summary.
You can check another answer by me on this here as well.
ViewModel with SelectList binding in ASP.NET MVC2
Let me know if you have any question.
-Soe
Most MVC frameworks have the ability to temporarily store a small bit of data just through the next request, for just this purpose. In ASP.NET MVC its called TempData, in Rails it's called :flash, etc.
This article explains how to use TempData:
One of the more annoying things to
deal with in Web programming is errors
on a form. More specifically, you want
to display error messages, but you
want to keep the previously entered
data. We've all had the experience of
making a mistake on a form that has 35
fields, only to be presented with a
bunch of error messages and a new,
blank form. The MVC Framework offers TempData as a place to store the previously entered information so that the form can be repopulated. This is
something that ViewState actually made
very easy in Web Forms, since saving
the contents of controls was pretty
much automatic. ... TempData is a dictionary,
much like the untyped ViewData.
However, the contents of TempData only
live for a single request and then
they're deleted.

MVC Multiple ViewPage items in aspx required

I need to pass in 2 objects to a page to access Model.NewsItems and Model.Links
(the first is a class of news item objects with heading, content etc and the Links are a set of strings for hyperlink depending on whether the system is up or down.
This is the page declaration
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<Tolling.Models.NewsItems>" %>
If I refer to Model.Items - I am fine.
However, if I refer to Model.HyperLink1, I am not.
How can you pass in multiple objects into the page?
I have tried importing both namespaces without success - i.e.
<%# Import Namespace="Tolling.Models.News" %>
<%# Import Namespace="Tolling.Models.HyperLinks" %>
Create a ViewModel class that contains both of your model collections and then pass that too the view:
Sample Controller:
var myNewModel = new MyNewModel()
{
NewsItems = new List<NewItem>(),
HyperLinks = new List<HyperLink>()
}
return View(myNewModel);
View page declaration:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MyNewModel>" %>
Then you can access them in your view with your new ViewModels properties:
<%= Model.NewsItems %>
<%= Model.Hyperlinks %>
You can pass extra data into the View by using ViewData, TempData, Session or Cache. I'd suggest you use ViewData. As described by MSDN:
Gets or sets a dictionary that
contains data to pass between the
controller and the view.

Resources