Reputation: 2055
I have a Razor View with a ViewModel and I need to extract the ID value from the model so I can create an ActionLink dynamically. The ID is also the parameter that is used to get to the View. This seems like it should be easy enough but I can't find an example of how.
Edit:
I'm using MVC 3
I want to be able to create an ActionLink with the ID of the model. So what I'm trying to do is something like this:
$(document).ready(function () {
**var id = @Model.ID;** //here is where I need help
var link = $("#PackingList");
var href = link.attr("href");
href = href.substring(0, href.length - 1);
href = href + id;
link.attr("href", href);
}
@Html.ActionLink("Print Shipping Report", "ShippingPackingList", new { id = 0 }, new { id = "PackingList" })
Upvotes: 0
Views: 7070
Reputation: 9931
Easiest way to get that ID is to put it in a hidden input element in your HTML, then grab the value in your javascript.
HTML:
@Html.HiddenFor(x => x.ID, new { id = "coolIdForThisHiddenElement" })
Docs on Html.HiddenFor: http://msdn.microsoft.com/en-us/library/ee703622.aspx
Then in your javascript to get that value:
var id = $('#coolIdForThisHiddenElement').val();
Edit: It looks like you're trying too hard in your javascript. You should be able to include the model's ID in your Html.ActionLink code. You should be able to do this:
@Html.ActionLink("Print Shipping Report", "ShippingPackingList", new { id = Model.ID }, new { id = "PackingList" })
Notice id = Model.ID instead of id = 0? That will put the ID from your model in that generated link.
Upvotes: 1