Khang Tran
Khang Tran

Reputation: 19

RedirectToAction in ASP.Net MVC

I'm using ASP.net MVC 4
I have a controller following:

public class PersonController : Controller
{
    public ActionResult Edit(int id)
    {
        //todo something.........
    }

    [HttpPost]
    public ActionResult Edit(PersonModel model)
    {
        //todo something.........
        return RedirectToAction("Edit", model.Id); // => Okay
    }

    public ActionResult Create()
    {
        //todo something............
    }

    [HttpPost]
    public ActionResult Create(PersonModel model)
    {
        //todo something........

        return RedirectToAction("Edit", new { id = model.Id } ); //=>Okay
        //return RedirectToAction("Edit", model.Id); // => exception???, but Edit Action is Okay**
    }
}

Upvotes: 0

Views: 797

Answers (2)

Rahul
Rahul

Reputation: 2307

By default MVC supports 'ID' andnot 'id' or any other:

In your code ::

public ActionResult Edit(int id)
{
    //todo something.........
}

here you have declared int id because of that ::

return RedirectToAction("Edit", model.Id);

this is not working.

If you have been declared your Edit action as::

public ActionResult Edit(int ID)
{
    //todo something.........
}

then you can use this::

return RedirectToAction("Edit", new { @Id = model.Id } );

Upvotes: 0

user3383479
user3383479

Reputation:

I think you got the exception because the RedirectToAction Method has 6 signatures and when you write RedirectToAction("Edit", model.Id); it can be considered as a string and will search for a controller with the name model.Id. Have a look here MSDN:RedirectToAction. Hope it will help you

Upvotes: 1

Related Questions