Thursday, May 22, 2014

Cannot assign <null> to anonymous type property (ASP.NET MVC object routeValues)

After reading an article called ASP.NET MVC Partial Rendering by Stewart Leeks, I decided to download the code sample and gave it a spin. As I reviewed each classes and controllers, I needed to implement some changes on saving (ActionResult decorated by [HttpPost]) attribute. The updates would be to pass a value to parameter linkId so that I can add new record after editing a new one.
The first solution I have in mind was to pass a -1 to linkID. This would work but, this will append a -1 to the url being requested.
Code:
return RedirectToAction("ListAndEdit", new { linkId = -1 });
Image:

The second solution was to pass an object to the routeValue. However, this would append a System.Object to the request url.
Code:
return RedirectToAction("ListAndEdit", new { linkId = new object()});
Image
The last solution I cam to think was to pass a null value to the routeValue. Unluckily, you can't assign a null value to an anonymous type property.
Code:
return RedirectToAction("ListAndEdit", new { linkId = null});
After googling for a few hours, I stumbled upon this article: Assigning null to anonymouse type which is the basis for the accepted solution below.
Code:
return RedirectToAction("ListAndEdit", new { linkId = null as object});
Image
As you can see from the image above, there is no parameter value to the requested post url.

0 comments:

Post a Comment