如何从视图发送字符串化的JSON来控制器MVC4视图、字符串、控制器、JSON

2023-09-10 22:07:13 作者:未来可期

我想送一个字符串化的JSON对象上按一下按钮。我想如下...在按钮单击我能够调用所需的操作方法,但它传递的参数 ..

I want to send a stringified Json object on button click. I am trying as follows... On button click I am able to call the required Action method, but it's passing null for the parameter..

MemberLogin.cshtml 的

<input type="button" value="» Continue" id="btnLogin" onclick="PostData();">

<script type="text/javascript">
    function PostData() {
        var ObjLogInDto = new Object();
        ObjLogInDto.UserName = $("#txtUserName").val();
        ObjLogInDto.Password = $("#txtMemberPassword").val();
        ObjLogInDto.CaptchaText = $("#txtCaptcha").val();
        var StringifiedData = JSON.stringify(ObjLogInDto);
        $.ajax({
            url: '@Url.Content("~/Member/MemberLogin/MemberLogin")',
            async: false,
            type: "POST",
            data: StringifiedData,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            error: function (jqXHR, textStatus, errorThrown) {
                alert("ERROR:" + jqXHR + "-" + textStatus + "-" + errorThrown);
            },
            success: function (data, textStatus, jqXHR) {
                alert("SUCCESS:" + data.Message);
            }
        });
    }
</script>

Action方法

Action method

[HttpPost]
    public ActionResult MemberLogin(string JsonStr)
    {
        var ObjMemberLoginDto =
            new JavaScriptSerializer().Deserialize<MemberLoginDto>(JsonStr);
    }

我正在为这个空 JsonStr 。 注:我已经包括Json2.js。在阿贾克斯 StringifiedData 呼叫保持字符串化的数据。如 {用户名:TEST13361,密码:testpswd,CaptchaText:gz8h4}

I am getting null for this JsonStr. Note:I have included Json2.js. StringifiedData in ajax call holds stringified data. as {"UserName":"TEST13361","Password":"testpswd","CaptchaText":"gz8h4"}

推荐答案

的contentType'在你的$就财产(...)的配置是有问题的。 无论是删除的contentType,这样它会被设置为默认或者设置正确的内容类型。 你可以找到更多的内容类型这里

'contentType' property in your $.ajax(...) config is having problem. Either remove the contentType so that it would be set to default or set a proper content type. You can find more on content type here

另外,作为@Jai建议,你需要用数据在阿贾克斯(...)的设置是一个键 - 值对与重点相同的动作方法的参数名称以进行适当的模式结合。

Also as @Jai suggested, you need to wrap the "data" in ajax(...) setting to be a key-value pair with Key same as that of action method's parameter name for a proper modal-binding.