开发者

Spitting out a Index view using parameters

开发者 https://www.devze.com 2022-12-28 20:17 出处:网络
I\'m using ASP.MVC and trying to learn... I have the following controller // get all authors public ActionResult Index()

I'm using ASP.MVC and trying to learn...

I have the following controller

    // get all authors
    public ActionResult Index()
    {
        var autores = autorRepository.FindAllAutores();

        return View("Index", autores);
    }

    // get authors by type
    public ActionResult Index(int id)
    {
    开发者_运维问答    var autores = autorRepository.FindAllAutoresPorTipo(id);

        return View("Index", autores);
    }

If I try http://server/Autor/1 I get a 404 error. Why is that?

I even tried to create a specific method ListByType(int id) and the correspondent view, but that does not work too (URL: http://server/Autor/ListByType/1)

Any ideas?

EDIT Oh, the http://server/Autor works just fine. The method without parameters is spitting out my view correctly.


Assuming your class is called AutorController, and assuming you have the default route configuration of

{controller}/{action}/{id}

You should be able to request

/Autor/Index/<anything>

However, you seem to be a bit confused on the action methods. You could combine your action methods like so:

public ActionResult Index(int? id)
{
    var autores; // I know this wont compile - but without knowing what type FindAllAutoRes returns, I can't make a specific type for this example
    if(id.HasValue)
        autores = autorRepository.FindAllAutoresPorTipo(id);
    else
        autores = autorRepository.FindAllAutores();

    return View(autores); // Will automatically select the 'Index' View
}

MVC will select the first valid action method that corresponds to your route data - so if you request /Autor/Index/3, you will get the first action method, but since it has no parameters, the id route data is not bound to anything.

0

精彩评论

暂无评论...
验证码 换一张
取 消