Passing unstructured JSON between jQuery and MVC Controller Actions

后端 未结 2 1635
刺人心
刺人心 2021-01-23 23:11

There is quite a lot of helpful information on MVC model binding. My problem stems from the fact that I am trying to avoid creating strongly typed data in my MVC application as

相关标签:
2条回答
  • 2021-01-23 23:34

    You could use the serializeArray method. Let's suppose that you have a form containing the input elements which could be of any type and you want to invoke the following controller action:

    public ActionResult CaptureInput(Dictionary<string, string> values)
    {
        ...
    }
    

    here's how you could proceed:

    <script type="text/javascript">
        var values = $('form').serializeArray();
        var data = {};
        $.each(values, function (index, value) {
            data['[' + index + '].key'] = value.name;
            data['[' + index + '].value'] = value.value;
        });
    
        $.ajax({
            url: '@Url.Action("CaptureInput")',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (result) {
                alert('success');
            }
        });
    </script>
    
    0 讨论(0)
  • 2021-01-23 23:41

    Not exactly what you're after but maybe the resolution of this issue would give you a partial workaround, by allowing you to bind to a simple wrapper object with an embedded Dictionary. It might even allow binding direct to a Dictionary. Not sure... You might also need to explicitly set the json ContentType header in your $.ajax call

    "JSON model binding for IDictionary<> in ASP.NET MVC/WebAPI"

    0 讨论(0)
提交回复
热议问题