Get method by different parameter than id

0

How can I change this Get method so that instead of looking for the ID, I look for another parameter of the model.

 [ResponseType(typeof(LecturaCummins))]
    public IHttpActionResult GetLecturaCummins(int id)
    {
        LecturaCummins lecturaCummins = db.LecturaCummins.Find(id);
        if (lecturaCummins == null)
        {
            return NotFound();
        }

        return Ok(lecturaCummins);
    }
    
asked by jm167 08.05.2018 в 01:56
source

1 answer

0

It simply changes the type of parameter that it collects, example:

    [HttpGet]
    public IHttpActionResult GetLecturaCummins(string nombre)
    {

        var lecturaCummins = db.LecturaCummins.Where( p => p.Nombre == nombre));

        if (!lecturaCummins.Any())
        {
            return HttpNotFound();
        }

        return Ok(lecturaCummins);
    }

and if you notice I have modified the if since Where always returns a collection not null , if you want you can change Where by FirstOrDefault and leave your if as is. This whole example works well when you pass the parameters using an example form:

    @using (Html.BeginForm(
    "GetLecturaCummins", "Lectura", FormMethod.Get))
{
    <input type="text" name="Nombre"/>
    <input type="submit" value="buscar"/>
}

Your problem may be that you want to pass the name value, (which is a string) as a parameter in an asp path. example http://localhost:port/LecturaCummins/GetLecturaCummins/nombre_del_atriburo . If this is the case, the value expected by your method would arrive null, this happens because your project is configured to receive routes of type Controller / Action / int: Id, in order to receive a string in your route, just go to RouteConfig.cs and add:

routes.MapMvcAttributeRoutes();

would fit you like this:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Already above your method add the following to allow you to receive string:

        [Route("NombredetuController/GetLecturaCummins/{nombre:alpha}")]
        [HttpGet]
        public IHttpActionResult GetLecturaCummins(string nombre){
        ....
        }

I hope it helps you

    
answered by 08.05.2018 в 20:59