c# - 为什么这个 javascript 对象不转换为 C# 类对象?

标签 c# javascript jquery ajax asp.net-mvc-4

我正在开发一个小型测试台应用程序,您可以在其中为应用程序提供音符名称、符号和 Octave 音程,它会输出音符应发出的频率。

我在通过 AJAX 发送到服务器的 JavaScript 对象时遇到问题。但是,它根本不映射到操作上的类。

发送者代码是一段 JavaScript:

$someContainer.on('click', '.raise-pitch', function (e) {
    e.preventDefault();

    var $line = $(this).parents('.item-line'),
        // Cache GUI elements for this line.  Not pertinent.

    var data = {
        'model': {
            'NoteName': $noteName.val(),
            'Sign': $noteSign.val(),
            'Octave': $noteOctave.val()
        },
        'steps': 1
    };
    var dataString = JSON.stringify(data);

    $.ajax({
        type: 'POST',
        url: '@Url.Action("AlterPitch", "Home")',
        data: dataString,
        async: true,
        dataType: 'json',
        success: function (result) {
            // Unimportant things.
        }
    });
});

data对象中,您可以看到我有两个东西:modelsteps。这些步骤决定了我们改变音符的程度。我已验证 note namesignoctave 的值已将其放入数据对象中。 步骤是预先确定的。

但是,data 对象映射到 C# 端的 ViewModel,如下所示:

public class NoteViewModel
{
    public enum NoteSign
    {
        Natural,
        Sharp,
        Flat
    }

    public string NoteName { get; set; }
    public NoteSign Sign { get; set; }
    public int Octave { get; set; }
    public float Frequency { get; set; }

    private static readonly Dictionary<string, float> FrequencyLookup = new Dictionary<string, float>
        {
            {"C", 16.35f},
            {"C#", 17.32f},
            {"D", 18.35f},
            {"D#", 19.45f},
            {"E", 20.60f},
            {"F", 21.83f},
            {"F#", 23.12f},
            {"G", 24.50f},
            {"G#", 25.96f},
            {"A", 27.50f},
            {"A#", 29.14f},
            {"B", 30.87f}
        };

    // Methods...not important for reasons below.
}

...它本身封装在一个独特的 View 模型中:

public class AlterPitchViewModel
{
    public NoteViewModel model;
    public int steps;

    public NoteViewModel AlterPitch()
    {
        model.ChangeStep(steps);
        return model;
    }
}

...或者至少应该如此。我在 Controller 方法中设置了一个断点:

[HttpPost]
public ActionResult AlterPitch(AlterPitchViewModel model)
{
    return Json(model.AlterPitch(), JsonRequestBehavior.AllowGet);
}

...但是模型为 null,这会导致 NullReference 异常。

模型没有序列化到在此上下文中发送的对象。显然我仍然做错了什么。 问题是...什么?

最佳答案

这种方法对我很有效。

服务器端:

首先,创建您的 ViewModel

public class TestViewModel
{
    public string Id { get; set; }
    public string Description { get; set; }
}

然后,在 Controller 中:

[HttpPost]
public ActionResult TestingViewModel(TestViewModel udata)
{
   // Stuff.
}

客户端:

function CallTestingViewModel() {

    // We create the javascript object based on the 
    // definition of our C# ViewModel class.
    var udata = {
        Id: 1,
        Description: 'This is a test.'
    };

    // Calling the C# method via AJAX.
    $.when(GenericAjaxCall('Home/TestingViewModel', false, udata)).then(function (result) {
        // do stuff
    });

}


// Return the AJAX call as a Promise Object
function GenericAjaxCall(controllerUrl, async, clientData) {
    return $.ajax({
        type: 'POST',
        async: async,
        url: controllerUrl,
        data: JSON.stringify(clientData),
        contentType: 'application/json;',
        dataType: 'json'
    });
}

希望有帮助。

关于c# - 为什么这个 javascript 对象不转换为 C# 类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22154039/

相关文章:

c# - 在运行时初始化抽象类中的静态字段

c# - 保存图像时如何找到一般 GDI+ 错误的原因?

c# - 实例化一个知道公共(public)​​基类的泛型类型

javascript - meteor 铁路由器 : Passing data between routes

javascript - 语义 div 结构与样式

jquery按钮淡入淡出,背景图像表现得很奇怪

c# - asp.net Razor Pages - 根据另一个选择列表的选择更新选择列表

JavaScript:控制台中显示的原型(prototype)函数

javascript - 如何根据 Angularjs 中的某些条件在 Controller 中创建作用域变量

javascript - 如何在另一个 Fancybox 关闭后打开一个 Fancybox?