【发布时间】:2018-07-19 20:45:43
【问题描述】:
我目前要做的是将一个 JSON 字符串从后端 C# 传递给 JavaScript 以填充下拉列表。当前发生的情况是,当我使用提供的链接中的信息时,我得到的只是“”的文字输出。我不明白为什么要这样做。如果有人能指出我在正确的方向上会很棒。
我一直在看的当前帖子:
Passing variable from ASP.net to JavaScript
我一直在尝试的方式是(示例):
C#代码:
protected string jsonFoodString { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:63591/");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/Meals/").Result;
if (response.IsSuccessStatusCode)
{
string foods = response.Content.ReadAsStringAsync().Result;
jsonFoodString = foods;
BindData();
}
}
}
Javascript:
var count = 1;
$(document).ready(function() {
$("#addItemButton").click(function() {
if (count <= 5) {
$("#ContentPlaceHolder1_AddMealContainer")
.append(
$("<div class=\"form-group\" id=\"MealItem_\"" +
count +
">" +
"<div class=\"row\">" +
"<label ID=\"AddItemLabel_1\" class=\"col-xs-4 control-label\">Item</label>" +
"<div class=\"col-xs-4\">" +
"<select ID =\"AddItemDropdownList_1\" data-html=\"true\" data-animation=\"true\" data-toggle=\"tooltip\" data-placement=\"top\" class=\"form-control\">" +
"</select>" +
"<div class=\"has-error\">" +
"<span class=\"help-block\">" +
"</span>" +
"</div>" +
"</div>" +
"</div>" +
"</div>")
);
count++;
var notParsedFoodString = "<%= jsonFoodString %>";
console.log(notParsedFoodString); //Produces a literal string of "<%= jsonFoodString %>"
} else {
alert("You can only add 5 food items to a meal");
}
});
$("#addItemButton").append("<input type=\"button\" value=\"Add Food Item\" id=\"AddMealItem\" class=\"btn btn-default btn-sm\">");
});
【问题讨论】:
-
我使用 web api 调用来检索数据。这是最好的方法吗?
-
“api/Meals/”背后的代码是什么?那个javascript块来自哪里? (一个 javascript 文件没有看到
<%=有什么特别之处,一个 aspx 可能会起作用) -
我使用异步 XMLHttpRequest() 来收集我的 JSON 字符串,然后将其解析到我的下拉列表中。所以一切都很好并且工作正常。
标签: javascript c# asp.net asp.net-mvc-4