I've been trying to fix a problem in my app for a couple of days now and I can't figure out what's happening.
I'm developing a MVC 4 application. I have a view in which there's a div that I load with more html with an ajax call that is executed on the $(function() { ... });
. That ajax call works fine.
Problems start when I make the second ajax call. I paste the code below :-
In the main view :-
<div class="body" id="loadedData">
</div>
<script type="text/javascript" charset="utf-8">
$(function(){
loadData("@Url.Action("Authorizations","User", new { id = Model.ID })");
});
function loadData(url){
$.ajax({
type: 'GET',
url: url,
success: function (data) {
$("#loadedData").html(data);
}
});
}
</script>
And the partial view that is loaded in the div it's this:
@if (ViewBag.UserAuths != null){
<table>
<tr>
<th>
Operations
</th>
<th></th>
</tr>
@foreach (var prod in ViewBag.UserAuths){
<tr>
<td>
@prod[0]
</td>
<td>
<a href="" onclick="loadData(@Url.Action("RevokeAccess", "User", new { id = ViewBag.UserID, op = Int32.Parse(prod[1])}));">Remove</a>
</td>
</tr>
}
</table>
}
The problem happens when I click on the link in the HTML that's loaded by ajax (Remove). When i click, the page 'blinks' but nothing happens. I've put a breakpoint in the RevokeAccess function in UserController and it never stops.
Please help!
Edit:
There's other thing, when i click on the link, in the Chrome console it's shown a "Uncaught SyntaxError: Unexpected token )" message, but it disappears very quickly, i don't know why.
As you are using jQuery don't use inline events. Bind click event using jQuery. As you are fetching Partial View you can use .load()
which is much simpler.
Script
<script type="text/javascript">
$(function(){
$("#loadedData").load("@Url.Action("Authorizations","User", new { id = Model.ID })");
$("#loadedData").on('click', '.anchor', function(event){
event.preventDefault();//Stop default action
$("#loadedData").load(
$(this).data('url'), //Url
{ id: $(this).data('id'), op : $(this).data('op')}, //Parameters
function(){
//Perform any action if any
}
);
})
});
</script>
Change Your Partials as
@if (ViewBag.UserAuths != null){
<table>
<tr>
<th>
Operations
</th>
<th></th>
</tr>
@foreach (var prod in ViewBag.UserAuths){
<tr>
<td>
@prod[0]
</td>
<td>
<a class='anchor' href="#" data-url='@Url.Action("RevokeAccess", "User")' data-id="@ViewBag.UserID" data-op="@Int32.Parse(prod[1])">Remove</a>
</td>
</tr>
}
</table>
}