MVC – Error#1

When working with MVC 2, one of the most favourite thing was the way MVC help us to route to our markup-pages ( .aspx pages).
If you follow the normal rule of MVC that will generate Views with name according to ActionName ( name of Actions in Controllers). You would not meet any problem with GET and POST.
Let me make this clear, for example you need a Delete action in PersonController, from this Action, you generate a View ( called Delete.aspx in View folder).
Now, you implement following code for [HttpGet] and [HttpPost] Delete methods like:
public ActionResult Delete(int id)
Person p = new Person();
foreach (Person pn in people)
if (pn.Id == id)
p.Name = pn.Name;
p.Age = pn.Age;
p.Id = pn.Id;
p.Phone = pn.Phone;
p.Email = pn.Email;

return View(p);

// POST: /Person/Delete/5

public ActionResult Delete(Person p)
foreach (Person pn in people)
if (pn.Id == p.Id)

return RedirectToAction("Index");

When you select Delete ActionLink in Index pages, you will be redirected to a confirming-page to ask if you really want to delete the item in list. This page look like this ( just resemble, not exactly, i take this picture from another sample ):

Let’s see what is that button ?

This means if you click this Delete button, a POST will be sent to Web server with parameter: ?productId=2

Now, how HttpRoutingModule works with this url, if not a well-formed url according to our definition :
Problem: our httppost Delete method will receive a junk Model object and our logic breaks !

So how to fix this, simply, in our http-post Delete method, we need to get the parameter that our browser sends in POST request by using request command like this:
int id = int.Parse(Request["productId"].ToString());

Then, do whatever you want with this id (like build an model object with this id…)

Ok, problem solved !
See ya.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: