First let me say I think this site is a Godsend, and I am extremely grateful for all I've learned. I have an MVC3 component I'm working with. I want to populate a selectlist and when the user selects one of the options, I want a to load a partial view with the data displayed. Everything works so far except I'm missing the piece that refreshes the partial view. When the page originally loads, I see the empty container in the code. I get no JS errors and Firebug shows the properly formatted HTML returned. So what part of the operation am I missing to refresh the partial view on the page? Please advise and thanx in advance.
The View:
<tr>
<th>Select a User to view their Roles:</th>
<td><%= Html.DropDownList("UserListForRoleView", list, "Please choose a User")%></td>
</tr>
<tr>
<td>
<% Html.RenderPartial("ViewUsersInRole");%>
</td>
</tr>
$(document).ready(function () {
$('#UserListForRoleView').change(function () {
var selectedID = $(this).val();
$.get('/UserAdminRepository/ViewUsersInRole/?user=' + selectedID)
});
});
THe Controller:
public ActionResult ViewUsersInRole()
{
string user = Request["user"];
string[] selectedRoles = Roles.GetRolesForUser(user);
List<string> data = new List<string>();
if (selectedRoles.Length > 0)
{
data = selectedRoles.ToList<string>();
}
else
{
data.Add("No data found");
}
ViewData["UsersinRole"] = data;
return PartialView("ViewUsersInRole");
}
The PartialView (in it's entirety):
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<ul>
<%
List<string> list = ViewData["UsersinRole"] as List<string>;
if (list != null && list.Count > 0)
{
foreach (string item in list)
{ %>
<li><%: item %></li>
<% }
}
%>
</ul>
append html in the td
like this:
<td id="partialcontainer">
<% Html.RenderPartial("ViewUsersInRole");%>
</td>
and append html in it:
$(document).ready(function () {
$('#UserListForRoleView').change(function () {
var selectedID = $(this).val();
$.get('/UserAdminRepository/ViewUsersInRole/?user=' + selectedID,function(response){
$('#partialcontainer').html(response);
})
});
});
Little Improved code, always use Url.Action
to generate url:
$(document).ready(function () {
$('#UserListForRoleView').change(function () {
var selectedID = $(this).val();
var url = '@Url.Action("ViewUsersInRole","UserAdminRepository")';
url+"?user="+selectedID;
$.get(url,function(response){
$('#partialcontainer').html(response);
});
});
});
I have modified a little your code to make it more clear and readable.
尝试RenderAction
<% Html.RenderAction("ViewUsersInRole");%>
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.