Category Archives: MVC 2.0

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;
break;
}
}

return View(p);
}

//
// POST: /Person/Delete/5

[HttpPost]
public ActionResult Delete(Person p)
{
foreach (Person pn in people)
{
if (pn.Id == p.Id)
{
people.Remove(pn);
break;
}
}

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 :
{Controller}/{Action}/{Id}
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.

Advertisements