保存按钮上的Ajax响应错误

时间:2016-12-19 13:13:08

标签: c# jquery asp.net-mvc entity-framework entity-framework-6

这里我从表单字段中保存数据,我想在列表页面中显示。但我无法得到清单。任何人都可以对此提出建议。

这是我的list.cshtml代码

var saveTrainingProgram = function () {

    console.log('in save');

    $.ajax({
        url: '/Affiliate/TrainingProgram/Save',
        type: 'POST',
        data: {
            trainingProgramName: ff.trainingProgramName.val(),
            colorCode: ff.colorCode.val()
        }
    }).done(function (response) {
        if (response.status === 'success') {



        } else {

        }


    }).fail(function (jqXHR, textStatus) {

        $.isLoading('hide');
    });


};


};

这是我的控制器代码:

[HttpPost]
[Authorize(Roles = "Affiliate")]
public ActionResult Save(string trainingProgramName, string colorCode)
{
    CbJsonResponse response = new CbJsonResponse();

    int errorCount = 0;
    List<string> errorMessages = new List<string>(5);


    if (string.IsNullOrEmpty(trainingProgramName))
    {
        errorCount++;
        errorMessages.Add("Error: The Training Program Name is required.");
    }

    if (string.IsNullOrEmpty(colorCode))
    {
        // This is not a required field, assign a default value.
        colorCode = CbConstants.TrainingProgramDefaultColorCode;
    }


    if (errorCount == 0)
    {
        Entities.TrainingProgram trainingProgram = new Entities.TrainingProgram();
        trainingProgram.Name = trainingProgramName;
        trainingProgram.ColorCode = colorCode;

   if (TrainingProgramRepository.Instance.SaveTrainingProgram(trainingProgram))
        {

            response.Status = "success";

            TrainingProgramListEntry listEntry = new TrainingProgramListEntry()
            {
                ID = trainingProgram.ID,
                Name = trainingProgram.Name,
                ColorCode = trainingProgram.ColorCode
            };

            // Include the list entry in the response.
            response.Data.Add(listEntry);
        }
    }
    else
    {
        response.Status = "failure";
        response.Meta.Add("errorCount", Convert.ToString(errorCount));
        response.Data.Add(errorMessages);
    }

    return Json(response, "application/json", System.Text.Encoding.UTF8, JsonRequestBehavior.AllowGet);
}

1 个答案:

答案 0 :(得分:0)

如果您使用的是ViewModel,则可以轻松解决此问题。尝试如下所示,让我们知道结果......

public class MyVmModel
{
    public string TrainingProgramName { get; set;}
    public string ColorCode { get; set;}
    public string Status { get; set;}

}


[HttpPost]
[Authorize(Roles = "Affiliate")]
public ActionResult Save(MyVmModel myVm)
{
    //your code here

    myVm.Status= "your message here"
    return Json(myVm);
}

Ajax的一部分:

$.ajax({
        url: '/Affiliate/TrainingProgram/Save',
        type: 'POST',
        data: {
            trainingProgramName: ff.trainingProgramName.val(),
            colorCode: ff.colorCode.val()
        }
        accept: 'application/json' //you have to give this here
})