在这里,我可以在动态创建的div上显示大学图像。现在我想得到用户选择的大学形象的id,然后使用该id显示选择大学提供的课程。有没有办法做到这一点?
protected void fetchUniversities()
{
List<University> uniList = new List<University>();
using (var dd = new UniversityContext())
{
uniList = UniversityController.fetchUniversitiesOfferCourses(dd);
}
Literal header = new Literal();
header.Text = "<div class=\"container\"><div class=\"row\"><h2>Apply For University</h2><p>Select your Prefferd University</p></div></div>";
CompanyPanel.Controls.Add(header);
foreach (var item in uniList)
{
Literal label1 = new Literal();
label1.Text = "<div class=\"container\"><div class=\"row\" >";
Literal lblTwo = new Literal();
lable2.Text = "<img src=\"/template/images/" + item.ImageName + "\" height=\"100%\"/>";
Literal lblLast = new Literal();
label3.Text = "</div></div>";
Panel1.Controls.Add(label1);
Panel1.Controls.Add(label2);
Panel1.Controls.Add(label3);
}
}
答案 0 :(得分:0)
通过转移到不同的框架并返回数据(例如JSON)以响应ajax查询(看一下ASP.NET MVC),你可以更好地实现这一点。
以下是使用您的示例实现此目的的一种方法,它有点麻烦,我没有测试过,但应该让您朝着正确的方向前进
添加如下方法:
[WebMethod]
public static string GetUniversityCourses(int universityId)
{
List<UniversityCourses> courses = ...
StringBuilder coursesHtml = new StringBuilder();
foreach(var course in courses) {
//Generate your html here
coursesHtml.Append("<div>" + course.Name + "</div>";
}
return coursesHtml.toString();
}
然后将此javascript代码添加到您的aspx文件中:
function GetUniversityCourses(id) {
$.ajax({
type: "POST",
url: "Default.aspx/GetUniversityCourses",
data: {"id": id,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
complete: function (jqXHR, status) {
$("#coursesContainer_" + id).html(jqXHR.responseText);
}
});
}
然后在您的服务器端代码:
lable2.Text = "<a href="javascript:void(0);" data-getcourseid=\"" + item.Id + "\"><img src=\"/template/images/" + item.ImageName + "\" height=\"100%\"/></a><div id=\"coursesContainer_\"" + item.Id + "</div><script>$('a[data-getcourseid=\"" + item.Id + "\"]').on('click', function() { GetUniversityCourses(" + item.Id + ")}</script>";