好的,这里是我如何通过使用ajax并避免使用AutoPostback一起来填充我的子类别。
创建一个对象,该对象表示要发回的选择列表json对象。
public class SelectItem
{
public string Id { get; set; }
public string Text { get; set; }
}
然后创建一个PageMethod的:
[WebMethod]
public static List<SelectItem> GetSubCategories(string Id)
{
// Returning dummy data for demo purposes
var subCats = new List<SelectItem>();
if (Id == "1")
{
subCats.Add(new SelectItem { Id = "1", Text = "1 Subs"});
}
else if (Id == "2")
{
subCats.Add(new SelectItem { Id = "2", Text = "2 Subs"});
}
return subCats;
}
添加脚本经理和EnablePageMethods
即
<asp:ScriptManager runat="server" EnablePageMethods="true">
</asp:ScriptManager>
更改您的下拉列表中使用ClientIDMode="Static"
<asp:DropDownList Id="ddlCategory" runat="server" ClientIDMode="Static">
<asp:ListItem Value ="1" Text ="One"></asp:ListItem>
<asp:ListItem Value ="2" Text ="Two"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList Id="ddlSubCategory" runat="server" ClientIDMode="Static">
</asp:DropDownList>
然后使用以下的jQuery:
<script type="text/javascript">
$(function() {
var $cat = $('#ddlCategory');
$cat.click(function() {
var catId = $cat.val();
$.ajax({
type: "POST",
url: "Default.aspx/GetSubCategories",
data: "{ Id: " + catId + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var subs = msg.d;
// empty selection
var $ddlSubCategory = $('#ddlSubCategory');
$ddlSubCategory.empty();
$.each(subs, function (index, sub) {
$ddlSubCategory.append($('<option/>', {
value: sub.Id,
text: sub.Text
}));
});
}
});
});
});
</script>
对不起,我从来没有回本。我必须做的其他事情突然变得更加紧迫。无论如何,我确实设法实现了这一点,但要避免这种Web方法只能是静态的限制并不容易。所以我最终发送了大量的信息给客户端(在隐藏的输入中),然后将它发送回web控件的参数到函数中。如果有更优雅的方式去做,我会很高兴! –
@MrLister没问题:紧急,我知道它会是什么样子。是的,不幸的是,你不得不把东西发回给客户。我现在主要在MVC工作,所有事情都必须发回去,所以我习惯了。它在网络表单中看起来有点脱节,但防止回发给出了良好的用户体验。祝好运与其余。 :) – hutchonoid