核心MVC和.ajax不向Controller中的ActionResult发送数据

时间:2016-10-27 01:04:30

标签: json ajax asp.net-mvc asp.net-core

这在MVC4 / 5中运行良好,但由于某种原因,在MVC Core中,我在ActionResult中的参数处接收NULL。我也试过它作为"新的" JsonResult,同样的情况 - NULL正在被接收。

在Fiddler看起来不错,JSONLint告诉我它是有效的JSON,所以我很困惑为什么我只看到NULL而不是我的数据。

这是POST的剪辑:

function saveClip() {
    console.log("Entered form save function");
    event.preventDefault();
    var formData = getFormData();
    console.log("After getting the form data: ", formData);
    var toSend = JSON.stringify({ clipData: formData });
    console.log("After stringify: ", toSend);

    $.ajax({
        type: "POST",
        url: "Clips/SaveClip",
        data: toSend,
        contentType: "application/json;",
        dataType: "json",
        success: function (response) {
            console.log("Success: ", response);
        },
        error: function (response) {
            console.error("Error: ", response);
        }
    });
};

function getFormData() {
    var publishDate = $("#publishDate").val();
    var category = $("#category").val();
    var headline = $("#headline").val();
    var clipUrl = $("#clipUrl").val();
    var copy = $("#copy").val();
    var notes = $("#notes").val();
    var source = $("#source").val();
    var relatedTo = $("#headlineList").val().length > 0 ? $("#headlineList").val() : null;
    var isNew = $("#isNew").checked ? true : false;

    return {
        PublishDate: publishDate,
        Category: category,
        Headline: headline,
        ClipUrl: clipUrl,
        Copy: copy,
        Notes: notes,
        Source: source,
        RelatedTo: relatedTo,
        IsNew: isNew
    };
};

这是我在控制器中的ActionResult / JsonResult:

    [HttpPost]
    public ActionResult SaveClip(string clipData)
    {
        if (null == clipData)
            return Json("No input received.");

        dynamic jsonObject = JsonConvert.DeserializeObject(clipData);

        using (var context = new ClipsSystemContext())
        {
            var clip = new Clip
            {
                PublicationDate = jsonObject.PublicationDate,
                Category = jsonObject.Category,
                Headline = jsonObject.Headline,
                Url = jsonObject.Url,
                Content = jsonObject.Content,
                Notes = jsonObject.Notes,
                Source = jsonObject.Source,
                IsNew = jsonObject.IsNew,
                RelatedTo = jsonObject.RelatedTo,
                AddedBy = Guid.Parse("eed800ab-573f-4453-8fe4-810b8e714edd")
            };

            context.Clip.Add(clip);

            var status = "Clip saved.";
            try
            {
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                status = ex.Message;
            }

            return Json(status);
        }
    }

最后,这里是Fiddler的Raw视图:

POST http://localhost:1711/Clips/SaveClip HTTP/1.1
Host: localhost:1711
Connection: keep-alive
Content-Length: 265
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:1711
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36
Content-Type: application/json;
Referer: http://localhost:1711/Clips
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Cookie: ai_user=PqmJn|2016-09-08T23:11:47.542Z
DNT: 1

{"clipData":{"PublishDate":"10/26/2016","Category":"ba6570f4-1316-4dd5-922e-4739eb9c6c64","Headline":"Ajax Top Story","ClipUrl":"http://www.google.com","Copy":"Ajax top story copy","Notes":"test notes","Source":"Wall Street Journal","RelatedTo":null,"IsNew":false}}

*编辑 - 10/28/2106 * 这是定义ClipModel和更新的ActionResult的类:

public class ClipModel
{
    public string Headline { get; set; }
    public string Content { get; set; }
    public Guid Category { get; set; }
    public string Source { get; set; }
    public string Url { get; set; }
    public bool IsNew { get; set; }
    public string Notes { get; set; }
    public Guid? RelatedTo { get; set; }
    public DateTime? PublicationDate { get; set; }
}


[HttpPost]
public ActionResult SaveClip(ClipModel clipData)
{
    if (null == clipData)
        return Json("No input received.");
    using (var context = new ClipsSystemContext())
    {
        var clip = new Clip
        {
            PublicationDate = clipData.PublicationDate,
            Category = clipData.Category,
            Headline = clipData.Headline,
            Url = clipData.Url,
            Content = clipData.Content,
            Notes = clipData.Notes,
            Source = clipData.Source,
            IsNew = clipData.IsNew,
            RelatedTo = clipData.RelatedTo,
            AddedBy = Guid.Parse("eed800ab-573f-4453-8fe4-810b8e714edd")
         };
         context.Clip.Add(clip);
         var status = "Clip saved.";
         try
         {
             context.SaveChanges();
         }
         catch (Exception ex)
         {
            status = ex.Message;
         }
         return Json(status);
    }
}

2 个答案:

答案 0 :(得分:0)

试试这个

 var urlR = '@Url.Action("SaveClip", "Exam")';       
    var formData = getFormData();
    var convertToString = JSON.stringify(formData);

    $.ajax({
        async: false,
        type: "POST",
        url: urlR,
        contentType: "application/json; charset=utf-8",          
        data: JSON.stringify({ clipData: convertToString }),
        cache: false,
        success: function (result) {
            alert("success");

        },
        failure: function (errMsg) {
            //hideprogressbar();
        },
        complete: function () {
            //hideprogressbar();
        }
    });

答案 1 :(得分:0)

将[FromBody]属性附加到Action方法:

[HttpPost]
public ActionResult SaveClip([FromBody]ClipModel clipData)