Reputation: 4122
I'm trying to inject a view using Ajax but it's not quite working. I know nothing about Ajax but I'm trying to learn. What am I missing here or am I completely wrong the way I'm doing this.
foreach(ect...) {
<tr>
<td>
<a href="#" onclick="AjaxStoryClick(@item.Id)" style="color:dodgerblue; font-weight: bold">@item.Name</a>
<script type="text/javascript">
function AjaxStoryClick(storyid) {
$.ajax({
url: '@Url.Action("UserStoriesList", "Estimate")',
type: 'POST',
data: storyid,
success: function(result){
$('#stories').html(result);
}
});
}
</script>
Controller:
public ActionResult UserStoriesList(int id)
{
ActiveEpicId = id;
var userstories = userRepository.Select().Where(x => x.EpicId.Equals(id)).ToList();
return PartialView("UserStoriesList",userstories);
}
Upvotes: 0
Views: 2375
Reputation: 1883
The Ajax call is not passing the value for the parameter 'Id' to the action method 'UserStoriesList', line 'data: storyid,' should be 'data: { id:storyid},'
As your action method 'UserStoriesList' has a not null-able id parameter, server will generate a error response:
You will not see the error response if there is no callback for the ajax error event and in debug mode the breakpoint in the action will not be hitted.
Here is updated script:
<script type="text/javascript">
function AjaxStoryClick(storyid) {
$.ajax({
url: '@Url.Action("UserStoriesList", "Estimate")',
type: 'POST',
data: { id: storyid },
success: function (result) {
$('#stories').html(result);
},
error: function (xhr) {
alert("Error: " + xhr.responseText);
}
});
}
</script>
Action method:
public ActionResult UserStoriesList(int id)
{
ActiveEpicId = id;
var userstories = userRepository.Select().Where(x => x.EpicId.Equals(id)).ToList();
if (Request.IsAjaxRequest())
return PartialView("_UserStoriesList", userstories);
else
return View("UserStoriesList", userstories);
}
Upvotes: 1
Reputation: 218702
Is UserStoriesList
Action method of Type HttpPost
? Your Ajax request is of type POST
. So it will be only handled by HttpPost type UserStoriesList action method.
[HttpPost]
public ActionResult UserStoriesList(int id)
{
// your code goes here
}
If your ActionMethod is not of Type HttpPost
(that means it is of HttpGet
type) , you can use a jquery get ajax call to get the data
Make sure your parameter name in your ajax call is same as of the parameter name in your action method.
function AjaxStoryClick(storyid) {
$.get('@Url.Action("UserStoriesList", "Estimate")',{id : storyid},function(result){
$('#stories').html(result);
});
}
}
Upvotes: 3