After reviewing A LOT of questions and Internet data, I’ve solved a problem of mine with getting URL parameter from MVC3 application correctly.
Thing is that there wasn’t a fault in coding, but in routing (I’m not so good with routing…).
Here’s the current issue.
http://localhost:51561/Report/Details/1
This is the way my application presents Report details, which is good. But when it does it like this, I can’t get value from URL parameter, like this
Request.QueryString["id"]
But, when I manually type in URL http://localhost:51561/Report/Details?id=1 it works…
Thing is i like the first URL type, but I don’t know how to get parameter from it…
Help, please…
Update:
My Controller actions:
public ViewResult Details(int id)
{
Report report = db.Reports.Find(id);
ViewBag.TestID = Request.QueryString["id"].ToString();
return View(report);
}
public ActionResult Show(int id)
{
Report report = db.Reports.Find(id);
var imageData = report.Image;
return (File(imageData, "image/jpg"));
}
My View:
<div class="display-label">Picture</div>
<div class="display-field">
<img alt="image" src="<%=Url.Action("Show", "Report", new { id = ViewBag.TestID })%>" width="200px" />
</div>
First of all, you shouldn’t use
Request.QueryStringin your application. Apart from that, in the first URL, you don’t have a query string, and thus you can’t access it (also read this article on msdn aboutRequest.QueryString).I also would like to suggest you to go through the basic tutorial of ASP.NET MVC3, to be found here. Many things like your question are thoroughly explained there.
To answer your question now, in your first URL example, the
1in the URL is a parameter of your action (the Details action). You have to add this parameter to your method (action):UPDATE:
You have apparently the right action (method) declaration. Now, you can just use the parameter
id. So change theRequest.QueryString["id"]just by the variable (parameter)id.There is no need to apply
ToString()on the id, you shouldn’t make it when it isn’t necessary (you might need it somewhere else, later or so). Just put it in theViewBagas the original type.Your
Show()method is good :). You have now theidparameter as you needed. (Try to avoid too many parentheses, it makes it look messy and now so clear.)