Home > database >  How to pass query parameter value into HTML.Partial model?
How to pass query parameter value into HTML.Partial model?

Time:08-17

I have an MVC page (Not .Net Core) which contains the below code

@Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(1))

The query in the address bar is similar to ..../products/product?id=4

How could i pass in the query value of 4 (or whatever it might be) into the Model.Product(ID) which then calls some code in my database to retrieve that product?

Using a hardcoded value works so im not sure if i should be doing this differently or if there is a better approach?

Finally hopefully this wont make a difference but once i have this working i would like to change the URL to something more friendly i.e. ..../products/product/4

CodePudding user response:

method 1 : get route data in razor view

{
   var id = Context.GetRouteData().Values["id"];
}
 
@Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(id))

method 2 : pass id with controller (viewbag or model)

public ActionResult Product(int id){
  var model= {
       ...
       Id = id
   }
   //ViewBag.Id = id;
   return View(model)
}

view:

@model ViewModel
{
 var id = int.Parse(ViewBag.Id); // alternative sln.
}

@Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(Model.Id))

CodePudding user response:

I have been using the below method and it works for me you can also try this

@Html.Action(, , new { @<Parameter_name> = })

Eg: @Html.Action("DetailsProducts", "CREDITNOTEs", new { @id = Model.ID })

  • Related