如何使用AJAX调用将数据从JavaScript传输到模型

时间:2016-01-19 03:14:44

标签: javascript jquery ajax asp.net-mvc razor

我的实施

模型

namespace Game.Models
{
    public class Lev_model
    {
        public static string GetJsonFile(string Level)
        {           
                string Data;
                string selectedLevel = "One";
                string one = System.Web.HttpContext.Current.Server.MapPath(@"~/Data//lvl-one.json");
                string two = System.Web.HttpContext.Current.Server.MapPath(@"~/Data//lvl-two.json");
                if (selectedLevel == "One")
                {
                    Data = File.ReadAllText(one);
                }
                else if (selectedLevel == "Two")
                {
                    Data = File.ReadAllText(two);
                }
                else
                {
                    Data = "Default";
                }

                return Data;                      
        }        
    }
} 

查看

//AJAX call to change the selectedLevel to "one" or "two"


 var lvlData = "One"

        $.ajax({
            url: '@Url.Action("GetLevelData", "Home")', 
            type: "POST",
        data: {strLvl: lvlData},
        success: function(response) {
            response ? alert("It worked!") : alert("It didn't work.");
        }

控制器

[RequireHttps]
        public ActionResult GetLevelData(string strLvl)
        {
            var data = Lev_model.GetJsonFile(strLvl);
            return Json(data, JsonRequestBehavior.AllowGet);
        }

我的问题

如何添加View/ AJAX调用以更改模型的值。请注意,我是硬代码selectedLevel to "One",但我希望将其设置为动态,这意味着我可以更改该值,以便它只能加载一个JSON文件。

2 个答案:

答案 0 :(得分:1)

 $.ajax({
        type: "POST",
        url: serviceUrl,
        data: { strLvl: YourData},
        success: function (response) {
             //Do some thing
        },
        error: function () {
             //Error message
        }
    });

答案 1 :(得分:1)

试试这个 -

        $.ajax({
            type: "POST",
            url: '/controller/GetLevelData',
            data : JSON.stringify({ 'strLvl': lvlData }),
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
            },
            error: function () {
            }
        });