Reputation: 8225
I have a button in my .cshtml page. I want to pass the id of the button to the controller action. Here is what I have currently:
@foreach (var item in Model)
{
<div id="report">@Html.ActionLink(@item.Name, "Parameterize", "Report", new { Id = @item.Id }, null )</div><br /><br />
<input id="@item.Id" type="button" onclick="Test()" class="button1" value="Update" />
}
In Firebug I can see that the id is properly fetched:
Now in the js code, here is what I am trying, but for some reason the id is still null in the controller action:
<script type="text/javascript">
function Test() {
var itemId = $('#report').attr('id');
var url = '@Url.Action("UpdateReport/", "Report")';
var data = { Id:itemId };
$.post(url, data, function (result) {
var id = '#postedFor' + postId;
$(id).html(result);
});
}
</script>
In the controller action I have this, and the id is null at this time:
public ActionResult UpdateReport(string id)
{
return View("Index");
}
Every advice is more then welcome. Thanks in advance, Laziale
Upvotes: 1
Views: 8678
Reputation: 16032
This line:
var itemId = $('#report').attr('id');
is fetching the id of your div with the id report.
You want to pass the button to the function test() and use it to get its id:
<input id="@item.Id" type="button" onclick="Test(this)" ...
And then in your js Test() function:
var itemId = $(this).attr('Id');
Also note, that the attribute names are case sensitive. You wrote "id", but your attribute is called "Id".
Upvotes: 1
Reputation: 413682
You're generating many <div>
elements with exactly the same "id" value. The "id" of an element must be unique on the whole page, or else weird things will happen.
Thus, $('#report')
is not going to work properly. Maybe you could do:
@foreach (var item in Model)
{
<div id="[email protected]">@Html.ActionLink(@item.Name, "Parameterize", "Report", new { Id = @item.Id }, null )</div><br /><br />
<input id="@item.Id" type="button" onclick="Test()" class="button1" value="Update" />
}
Alternatively, you could pass the input element directly to the handler:
<input id="@item.Id" type="button" onclick="Test(this)" class="button1" value="Update" />
Then:
function Test(item) {
var itemId = item.id,
var url = '@Url.Action("UpdateReport/", "Report")';
var data = { Id:itemId };
$.post(url, data, function (result) {
var id = '#postedFor' + postId;
$(id).html(result);
});
}
Upvotes: 1
Reputation:
Your selector looks off:
var itemId = $('#report').attr('id');
That is going to get the id
value of an element with an id
of report
. I don't think that's what you're looking for.
Upvotes: 0