Help with ASP MVC routes (3 routes for the same action)

Asked

Viewed 87 times

1

I have a controller:

public class imoveisController : Controller
{
    public ActionResult Index(int idEstado = 0, int idCidade = 0, int[] idRegiao = null)
    {
        string IdEstado;
        string IdCidade;
        int[] IdRegiao;

        #LeOuGravaCookie

        #region MontaViewBags

        #region RetornaBairros

        #region RetornaImoveisDessesBairros

        return View(ImoveisRetornados);
    }
}

In the view there is a form where the user can select 1 state and 1 city and a set of neighborhoods. And when submitted it returns to the Index action that instead of reading this data a cookie will receive from the form, do the search and return the properties. Working 100% straight.

My problem is that when returning it displays to the user the following url:

meusite/immovable

And I need to return depending on what the user selects in the form If he informed only the state:

meusite/immobile/{stateInformable}

If he also selected a city:

meusite/imoveis/{stateInformado}/{Cidadeinformada}

Could someone help me do that?

1 answer

1


You can use the following strategy:

[RoutePrefix("home")]
public class HomeController : Controller
{
    [HttpGet, Route("inicio")]
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost, Route("inicio/{uf?}/{municipio?}")]
    public ActionResult Index(string uf, string municipio)
    {
        return RedirectToAction("Busca", new { uf = uf, municipio = municipio });
    }

    [Route("busca/{uf?}/{municipio?}")]
    public ActionResult Busca(string uf, string municipio)
    {
        return View("Index");
    }    
}

Form with the fields:

@{
    ViewBag.Title = "Home Page";
}

@using (Html.BeginForm("Index", "Home"))
{
    <input name="uf" id="uf" type="text" />
    <input name="municipio" id="municipio" type="text" />
    <input type="submit" value="BUSCAR" />
}

//Lembrando que é necessário configurar os MapMvcAttributeRoutes no arquivo RouteConfig.cs
routes.MapMvcAttributeRoutes();

When you submit the report it will send to the Action Search with new URL.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.