Reputation: 384
I have this helper code
@helper GetTreeView(List<MvcTreeview.Models.Category> siteMenu, int parentID)
{
foreach (var i in siteMenu.Where(a => a.ParentID.Equals(parentID)))
{
<li>
@{var submenu = siteMenu.Where(a => a.ParentID.Equals(i.ID)).Count();}
@if (submenu > 0)
{
<span class="collapse collapsible"> </span>
}
else
{
<span style="width:15px; display:inline-block"> </span>
}
<span id="Category">
<a href="#" id="@i.ID">@i.CategoryName</a>
<b></b>
</span>
@if (submenu > 0)
{
<ul>
@Treeview.GetTreeView(siteMenu, i.ID)
@* Recursive Call for Populate Sub items here*@
</ul>
}
</li>
}
}
and i want to pass the id to a Action method of a controller. How to pass the id from view to a action method in controller.
$('#Category').click(function () {
url = '@Url.Action("Index", "TestDetails");
$.ajax({
url: url,
type: 'POST',
success: function (returnData) {
},
error: {
}
});
});
How can i get the id in the second snippet of code.
Using that id i have to fetch some details using a action method in my controller.
Action Method
public ActionResult Index(int id)
{
TestDetail detail = new TestDetail();
detail = db.TestDetails.Single(a => a.ID == id);
return View(detail);
}
Upvotes: 0
Views: 615
Reputation: 3019
simply pass "this" to your onclick function
<span class="Category">
<a href="#" id="@i.ID" onClick="CategoryClick(this.id)">@i.CategoryName</a>
<b></b>
</span>
Javascript: (Edited)
<script type="text/javascript">
function CategoryClick(clicked_id)
{
alert(clicked_id);
url = '@Url.Action("TestDetails", "Index")'; //Url.Action(actionName, ControllerName)
$.ajax({
url: url,
data: {id: clicked_id}, //json format
success: function (returnData) {
},
error: {
}
});
}
</script>
Upvotes: 2
Reputation: 1503
Edit your helper as following:
@helper GetTreeView(List<MvcTreeview.Models.Category> siteMenu, int parentID)
{
foreach (var i in siteMenu.Where(a => a.ParentID.Equals(parentID)))
{
<li>
@{var submenu = siteMenu.Where(a => a.ParentID.Equals(i.ID)).Count();}
@if (submenu > 0)
{
<span class="collapse collapsible"> </span>
}
else
{
<span style="width:15px; display:inline-block"> </span>
}
<span >
<a class="Category" href="#" id="@i.ID">@i.CategoryName</a>
<b></b>
</span>
@if (submenu > 0)
{
<ul>
@Treeview.GetTreeView(siteMenu, i.ID)
@* Recursive Call for Populate Sub items here*@
</ul>
}
</li>
}
}
and the ajax call:
$('.Category').click(function () {
url = '@Url.Action("Index", "TestDetails")';
$.ajax({
url: url,
type: 'POST',
data: "{'id': " + $(this).attr("id") + "}",
success: function (returnData) {
},
error: {
}
});
});
Upvotes: 1