使用Ajax以MVC模式通过控制器发送数据

时间:2019-01-28 19:18:50

标签: javascript c# asp.net asp.net-mvc knockout.js

使用敲除功能,我试图将数据从UI发送到控制器。这是用于发送我的Ajax请求(PUT)的JavaScript

var model = new Object();
model.StudentID = "";
model.ActiveProgram = "";
model.ProgramDesc = self.programData();
model.Cohorts = self.associationData();
model.LoadIntent = self.loadIntentData();
model.Francophone = self.frenchData();
model.Gender = self.genderData();

    $.ajax({
        url: putStudentRegRequirementsUrl,
        type: "PUT",
        contentType: jsonContentType,
        dataType: "json",
        data: JSON.stringify(model),
        //jsonData:model,
        success: function (data) {
            $('#notificationHost').notificationCenter('addNotification', { message: "Updated.", type: "info" });
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status != 0)
            {
                $('#notificationHost').notificationCenter('addNotification', { message: "Unable to update registration requirement.", type: "error"});
            }
        }
    });

但是当我调试它以查看我的控制器时,输入的字符串为空。这是我的控制器

 [HttpPut]
    public async Task<JsonResult> UpdateRegistrationRequirementAsync(string regRequirementJson)
    {
        try
        {
            var regRequirementModel = JsonConvert.DeserializeObject<RegistrationRequirement>(regRequirementJson);
            var response = await ServiceClient.L09PutRegistrationRequirementAsync(CurrentUser.PersonId, regRequirementModel);
            return Json(response);
        }
        catch( Exception ex)
        {
            Logger.Debug(ex, "Error updating Registration Requirement for user failed.");
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json("Error updating Registration Requirement.");
        }       
    }

2 个答案:

答案 0 :(得分:3)

Action将按名称解析来自客户端的参数,因此您需要传递名称为regRequirementJson的参数,其中包含您的json。因此,更改此行

data: JSON.stringify(model)

data: { regRequirementJson: JSON.stringify(model) }

并删除contentType: jsonContentType

或者您可以尝试其他方法。由于ASP.NET本身可以反序列化json,因此您可以保持js代码不变并将控制器更新为

[HttpPut]
public async Task<JsonResult> UpdateRegistrationRequirementAsync(RegistrationRequirement regRequirementModel )
{
    try
    {
        var response = await ServiceClient.L09PutRegistrationRequirementAsync(CurrentUser.PersonId, regRequirementModel);
        return Json(response);
    }
    catch( Exception ex)
    {
        Logger.Debug(ex, "Error updating Registration Requirement for user failed.");
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json("Error updating Registration Requirement.");
    }       

答案 1 :(得分:1)

由于您要发送“ RegistrationRequirement”对象,因此在您的控制器中,您可以这样做:

[HttpPut]
    public async Task<JsonResult> UpdateRegistrationRequirementAsync(RegistrationRequirement registrationRequirement)
    {
        try
        {
            var response = await ServiceClient.L09PutRegistrationRequirementAsync(CurrentUser.PersonId, registrationRequirement);
            return Json(response);
        }
        catch( Exception ex)
        {
            Logger.Debug(ex, "Error updating Registration Requirement for user failed.");
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json("Error updating Registration Requirement.");
        }       
    }