Reputation: 8834
I have a page where I'm showing notes and after clicking a button I want to be able to add a note. The following code is the part how I tried to load the create note action result.
<script type="text/javascript">
(function() {
$('#load-partial'.click(function(){
$('#partial'.load('/EntityController/CreateNote/');});
})();
</script>
<div id="partial"></div>
<button type="button" id="load-partial" />
However, clicking the button does not do anything. What goes wrong here?
Upvotes: 1
Views: 1474
Reputation: 22860
Very good suggestions from Darin Dimitrov. To go to the next level
You need to use url helpers: $('#partial').load('@Url.Action("CreateNote", "Entity")');
To make this unobtrusive (and move the java script to a file), you need to use the @URL helper to set an action attribute/value, then harvest the action attribute value in the JavaScript. In my pending DropDownList tutorial I do the following:
@using (Html.BeginForm("IndexDDL", "Home", FormMethod.Post,
new { id = "CountryStateFormID",
StateListAction = @Url.Action("StateList") })) {
-- then in the JavaScript
$('#CountriesID').change(function () {
var CountryStateFormID = $('#CountryStateFormID');
$.getJSON(CountryStateFormID.attr('StateListAction') + '/' + $('#CountriesID').val(), function (data) {
You should also use IE9/F12 developer tools or Chrome or FF to debug your code.
Upvotes: 1
Reputation: 1039468
What goes wrong here?
For starters you have lots of javascript errors in what you have shown. Also are not waiting for the DOM to be ready before subscribing to events like click
. You just created an anonymous function that you executed immediately without waiting for the DOM to be ready. It should be like this:
<script type="text/javascript">
$(function() {
$('#load-partial').click(function() {
$('#partial').load('@Url.Action("CreateNote", "Entity")');
});
});
</script>
<div id="partial"></div>
<button type="button" id="load-partial" />
Other than that there could be like gazillions of things can go wrong here (which unfortunately we cannot rule out from the poor code snippet you provided):
/EntityController/CreateNote/
url is probably wrong. You need to use url helpers: $('#partial').load('@Url.Action("CreateNote", "Entity")');
/EntityController
as controller name but according to conventions the Controller suffix is only use when naming your controller classes, but not when referencing an url. So the url should probably be /entity/createnote
(see previous reason for the correct way to generate urls).Upvotes: 1