我需要通过一个请求发布到带有JSON(最好)的Api控制器.

问题是传递数据和文件(上传图像).我的财产是空的(空的).

我看了相当多的博客,但似乎不能让图片的数据通过.

public class SomeModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string City { get; set; }
    public HttpPostedFileBase Image { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string CountryCode { get; set; }
}


    [HttpPost]
    public void CreateContestEntry(SomeModel model)
    {
        // model.Image is always null
        // .. get image here - the other properties no issues
    }

jQuery

    // create model for controller
    var model = {
        Name: $.trim($contestForm.find('[name="nombre"]').val()) + ' ' + $.trim($contestForm.find('[name="apellido"]').val()),
        Email: $.trim($contestForm.find('[name="email"]').val().toLowerCase()),
        City: $.trim($contestForm.find('[name="cuidad"]').val()),
        Title: $.trim($contestForm.find('[name="title"]').val()),
        Description: $.trim($contestForm.find('[name="description"]').val()),
        CountryCode: 'co',
        Image: $contestForm.find('[name="file-es"]')[0].files[0]  // this has the file for sure
    };

    $.ajax({
        url: '/Umbraco/api/ControllerName/CreateContestEntry',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(model),
        //data: $('#test-form').serialize(),  // tried this and using FormData()
        processData: false,
        async: false,
        contentType: 'application/json; charset=utf-8',
        complete: function (data) {

        },
        error: function (response) {
            console.log(response.responseText);
        }
    });

enter image description here

Blogs I've looked at:


当我try FormData$('#form1').serialize()方法时,我的provider.FileDataprovider.FormData也总是空的.我从方法中删除了model个参数,当我切换它时,断点正在命中.

    [HttpPost]
    public void CreateContestEntry()
    {
        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        try
        {
            // Read the form data.
            Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                // empty
            }

            foreach (var key in provider.FormData.AllKeys)
            {
                foreach (var val in provider.FormData.GetValues(key))
                {
                    // empty
                }
            }
            //return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch(Exception ex)
        {

        }
    }

SOLUTION:

Going off of @Musa's answer, here's the Api Controller code. I mapped the NameValueCollection to my model.

    [HttpPost]
    public void CreateContestEntry()
    {
        try
        {
            // get variables first
            NameValueCollection nvc = HttpContext.Current.Request.Form;
            var model = new WAR2015ContestModel();

            // iterate through and map to strongly typed model
            foreach (string kvp in nvc.AllKeys)
            {
                PropertyInfo pi = model.GetType().GetProperty(kvp, BindingFlags.Public | BindingFlags.Instance);
                if (pi != null)
                {
                    pi.SetValue(model, nvc[kvp], null);
                }
            }

            model.Image = HttpContext.Current.Request.Files["Image"];
        }
        catch(Exception ex)
        {

        }
    }

推荐答案

You can't upload a file(that is arbitrary binary data) with JSON as JSON is a text format. you'll have to use multipart form data.

// create model for controller
var model = new FormData();
model.append('Name', $.trim($contestForm.find('[name="nombre"]').val()) + ' ' + $.trim($contestForm.find('[name="apellido"]').val()));
model.append('Email', $.trim($contestForm.find('[name="email"]').val().toLowerCase()));
model.append('City', $.trim($contestForm.find('[name="cuidad"]').val()));
model.append('Title', $.trim($contestForm.find('[name="title"]').val()));
model.append('Description', $.trim($contestForm.find('[name="description"]').val()));
model.append('CountryCode', 'co');
model.append('Image', $contestForm.find('[name="file-es"]')[0].files[0]);  // this has the file for sure

$.ajax({
    url: '/Umbraco/api/ControllerName/CreateContestEntry',
    type: 'POST',
    dataType: 'json',
    data: model,
    processData: false,
    contentType: false,// not json
    complete: function (data) {
        var mediaId = $.parseJSON(data.responseText); //?

    },
    error: function (response) {
        console.log(response.responseText);
    }
});

Json相关问答推荐

try 将文本标记放置在条形图上的同一高度

使用 jq 获取所有嵌套键和值

如何使用 JOLT 将带有列表的 JSON 项目取消列出为多个项目?

使用 Groovy 将 XML 转换为 JSON

jq - 将父键值提取为子元素旁边的逗号分隔值

为什么解析的字典相等而腌制的字典不相等?

JSON 字段的多个名称

使用 jq 同时迭代数组

可以通过 POST 使用 EventSource 传递参数的服务器发送事件 (SSE)

ASP.NET MVC - 将 Json 结果与 ViewResult 结合起来

JSON.NET JsonConvert 与 .NET JavaScriptSerializer

将 CoffeeScript 项目转换为 JavaScript(不缩小)?

如何将有向无环图 (DAG) 存储为 JSON?

嵌套 JSON:如何向对象添加(推送)新项目?

从 JSON 创建 Hashtable

杰克逊:反序列化 for each 值都具有正确类型的 Map

如何转换为 D3 的 JSON 格式?

Protocol Buffer vs Json - 何时 Select 一个而不是另一个

如何对 jq 中的 map 数组中的值求和?

使用 C# 调用 json