问题
I have a div with a partial inside somewhere on the page. I have a event on a button. How could I write a Javascript that takes the div and reloads it and also reloads the partial view.
I have this in another view. But I can't do it like this now. But I need the same thing to happen only execute by a jQuery not directly in the page. Can i run maybe simular ajax code in the jQuery script because its javascript too isn't it?.
<% using (Ajax.BeginForm("EditFeiertag", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "feiertage" }))
{ %>
<div id="feiertage">
<% Html.RenderPartial("FeiertagTable"); %>
</div>
<% } %>
I would help me if I could run the script above by start a click event or something like that
回答1:
Lets start with some basic controller actions:
public class FeiertagController
{
IFeiertagService feiertagService = new FeiertagService();
public ActionResult EditFeiertag()
{
// ... return your main edit view
return View();
}
// Will be called by your jquery ajax call
public PartialResult GetFeiertagTable()
{
var feiertagData = messageService.getLatestFeiertagData();
var viewModel = new FeiertagViewModel();
feiertagViewModel.feirtagTableData = feiertagData;
return PartialView("FeiertagTableView", viewModel);
}
}
So, EditFeiertag() is used to render your whole edit page, and that page will make a call to GetFeiertagTable() when it wants to asynchronously render your partial view.
Now, on your view, lets say you have something like:
<div id="Container">
<div id="LeftPanel">
// ... Some menu items
</div>
<div id="RightPanel">
<a id="ReloadLink" href="#">Reload Table</a>
<div id="FeiertagTable>
<% Html.RenderPartial("FeiertagTable", Model.feiertagTableData); %>
</div>
</div>
</div>
This works fine and will load your table once. But you want to make the Feiertag table reload if you click a certain element (in our case the #ReloadLink).
Add the following to portion of your page:
<head>
<script src="../../Scripts/Jquery/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#ReloadLink').click(function(e)
{
e.preventDefault(); // stop the links default behavior
$('#FeiertagTable').load('/Feiertag/GetFeiertagTable');
});
});
</script>
</head>
That will then add an event on the click event for your reload link that will call a jquery load() method. This method is a simplified ajax get request and it will replace the contents of the selected div (FeiertagTable), with what is returned.
Our GetFeiertagTable() controller action will return the partial view, which is then inserted into that div.
I hope this gets you pointed in the right direction!
来源:https://stackoverflow.com/questions/1433419/how-can-i-reload-a-div-with-a-partialview-in-asp-net-mvc-using-jquery