0

I am trying to pass an id to the URL, However I cant hard code the ID but I need to pass the id from the model.

It is basically a collection of a particular type of model displayed as a table. When the user clicks on the id value of the table i need to be able to pass the id to the URL so that it can open a corresponding detailed page of the same.

<a href="~/Instance/Details/[email protected](modelitem => item.Id)">   @Html.DisplayFor(modelitem => item.Id)</a>

This is what I am trying, need help:).

1
  • 2
    modelitem => item.Id this looks wrong. Shouldn't it be modelitem => modelitem.Id? Commented Aug 20, 2018 at 19:41

1 Answer 1

6

First of all, use the Url.Action method to generate the correct relative url to the action method.

@foreach (var item in SomeCollection)
{
  <div>
       <a href="@Url.Action("Details","Instance",new { id = item.Id })"> 
                                            @Html.DisplayFor(modelitem => item.Id)
       </a>
  </div>
}

The Url.Action method will generate the url value to details action method, which includes the item.Id value in the url.

Assuming Instance is the controller name where your Details action method is present with id parameter.

public class InstanceController : Controller
{
   public ActionResult Details(int id)
   {
      return Content("Details of "+id);
      // to do : return a view with data queried using id
   }
}
Sign up to request clarification or add additional context in comments.

6 Comments

new { id = item.Id } should probably be new { id = Model.Id }
@LewsTherin He is doing it inside a collection. So it should be the item he is loop is currently executing, which is item.Id.
@Sam Axe I updated your edit. Since it is a loop, it should be modelitem => item.Id. If you use modelitem => modelitem .Id, it is not valid. You will get an error from razor.
Oh okay, I missed that. Thanks for updating your answer.
modelitem => item.Id still doesn't make any sense to me. The input variable modelitem isn't used in that lambda expression. Shouldn't it still be modelitem => modelitem.Id? Won't item be passed in to the modelitem input parameter when the lambda expression is evaluated?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.