I'm new with ASP.NET MVC 4. I have followed the tutorial to load partial view without refreshing whole page. The problem is that it only reloads at first time. In my Index.cshtml
file:
<div id="detailsDiv">
</div>
<script type="text/javascript">
$('.setImage').click(function () {
var url = "/Home/Test";
var name = $(this).val();
$.post(url, { Name: name}, function (data) {
$("#detailsDiv").replaceWith(data);
});
})
</script>
In my HomeController.cs
file:
[HttpPost]
public ActionResult Test(string Name)
{
ConfigurationData cd = new ConfigurationData(Name, "xyz");
return PartialView("Test", cd);
}
My Test.cshtml
:
@using Wordrific.Models.ParseFolder
@model ConfigurationData
<p id="abcde">@Model.ConfigurationVariables</p>
<p id="abcde">@Model.GameRules</p>
<p>test</p>
My problem is that it only reloads only once. I set the break point on the Test.cshtml
file. I see the name is changed in the debug log but the browser does not update new data.
The only thing I can see, so far (until I get your full HTML), that might cause this is not using a DOM ready handler.
eg
<script type="text/javascript">
$(function(){
$('.setImage').click(function () {
var url = "/Home/Test";
var name = $(this).val();
$.post(url, { Name: name}, function (data) {
$("#detailsDiv").replaceWith(data);
});
});
})
</script>
$(function(){your code here});
is a shortcut for $(document).ready(function(){your code here});
Without this, correct operation would depend on the placement of the script within the page. If it preceded the elements with `class=setImage' there is a chance the code will fire before the elements are loaded.
Another way to avoid this sort of issue is using a deferred event handler.
eg
<script type="text/javascript">
$(document).on('click', '.setImage', function () {
var url = "/Home/Test";
var name = $(this).val();
$.post(url, { Name: name}, function (data) {
$("#detailsDiv").replaceWith(data);
});
});
</script>
This example listens for click
events that bubble-up to the document
level (which will always be present), then applies a jQuery filter to match elements, then applies the function to any matching elements that caused the event .
As a general rule though, use a DOM ready handler.
$("#detailsDiv").replaceWith(data);
replaceWith is replacing the whole detailsDiv that is why the second attempt is failing because it cannot find the detailsDiv anymore. Use the following code instead.
$("#detailsDiv").html(data);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.