I am currently working my way through the Apress ASP.NET MVC2 book, and I am a little bit confused as to the user of new { returnUrl } in the following code:
public RedirectToRouteResult RemoveFromCart(Cart cart, int productID, string returnUrl)
{
Product product =开发者_如何学运维 productsRepository.Products.FirstOrDefault(p => p.ProductID == productID);
cart.RemoveLine(product);
return RedirectToAction("Index", new { returnUrl });
}
Is it something to do with creating a new string, rather than simply passing a reference to the parameter passed in?
It's creating an anonymous type with a property returnUrl
which also has the value of returnUrl
. So it's like this:
var anon = new { returnUrl = returnUrl };
return RedirectToAction("Index", anon);
Using a name from the expression to determine the name of the property in an anonymous type is called a projection initializer.
Does that help to explain it to you at all? If not, you may want to revise anonymous types in general. They were introduced in C# 3, mostly for LINQ.
This is an anonymous type: http://msdn.microsoft.com/en-us/library/bb397696.aspx
That is an anonymous object. The property in the case above would create a new object with the string property 'returnUrl'.
In this context, it is specifying a url for the ActionResult to redirect the browser to.
That syntax creates an anonymous type. They're created on the fly as needed. In your example it creates a new object with one property and then passes it to the action as a parameter.
精彩评论