Reputation: 3
How to pass Id from javascript to Controller action in mvc3 on ajax unobtrusive form submit
My script
<script type="text/javascript">
$(document).ready(function () {
$("#tblclick td[id]").each(function (i, elem) {
$(elem).click(function (e) {
var ID = this.id;
alert(ID);
// var url = '@Url.Action("Listpage2", "Home")';
var data = { Id: ID };
// $.post(url,data, function (result) {
// });
e.preventDefault();
$('form#myAjaxForm').submit();
});
});
});
</script>
the how to pass Id on using $('form#myAjaxForm').submit(); to controller instead of
$.post(url,data, function (result) {
// });
My View
@using (Ajax.BeginForm("Listpage2", "", new AjaxOptions
{
UpdateTargetId = "showpage"
}, new { @id = "myAjaxForm" }))
{
<table id="tblclick">
@for (int i = 0; i < Model.names.Count; i++)
{
<tr>
<td id='@Model.names[i].Id'>
@Html.LabelFor(model => model.names[i].Name, Model.names[i].Name, new { @id = Model.names[i].Id })
<br />
</td>
</tr>
}
</table>
}
</td>
<td id="showpage">
</td>
Upvotes: 0
Views: 3520
Reputation: 727
I am not sure for $.post but I know window.location works great for me. Use this instead and hopefully you have good results :)
window.location = "@(Url.Action("Listpage2", "Home"))" + "Id=" + ID;
replace $('form#myAjaxForm').submit(); with this code and nothing looks blatantly wrong with your jscript.
Upvotes: 1
Reputation: 218702
I would avoid using the Ajax Beginform
helper method and do some pure handwritten and Clean javascript like this
<table id="tblclick">
@foreach(var name in Model.names)
{
<tr>
<td id="@name.Id">
@Html.ActionLink(name.Name,"listpage","yourControllerName",
new { @id = name.Id },new { @class="ajaxShow"})
</td>
</tr>
}
</table>
<script>
$(function(){
$(".ajaxShow")click(function(e){
e.preventDefault();
$("#showpage").load($(this).attr("href"));
});
});
</script>
This will generate the markup of anchor tag in your for each loop like this.
<a href="/yourControllerName/listpage/12" class="ajaxShow" >John</a>
<a href="/yourControllerName/listpage/35" class="ajaxShow" >Mark</a>
And when user clicks on the link, it uses jQuery load
function to load the response from thae listpage
action method to the div with id showPage
.
Assuming your listpage
action method accepts an id parameter and returns something
Upvotes: 1
Reputation: 8022
Just use a text box helper with html attribute ID.
@Html.TextBox("ID")
You can do this too:
var form = $('form#myAjaxForm');
$.ajax({
type: "post",
async: false,
url: form.attr("action"),
data: form.serialize(),
success: function (data) {
// do something if successful
}
});
Upvotes: 0