无法将C#字符串变量传递给JavaScript文件

时间:2018-02-09 06:11:11

标签: javascript c# asp.net asp.net-mvc-4

我目前要做的是将后端C#中的JSON字符串传递给JavaScript以填充下拉列表。目前正在发生的事情是,当我使用所提供链接中的信息时,我获得的所有信息都是""<%= jsonFoodString%>"的文字输出。我不明白为什么这样做。如果有人能指出我正确的方向,那将是伟大的。

我一直关注的当前帖子:

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\">");
});

1 个答案:

答案 0 :(得分:0)

我找到了我在这里寻找的答案!

XMLHttpRequest is deprecated. What to use instead?


let flippedImage = straightImage.withHorizontallyFlippedOrientation()