0

我只是无法弄清楚我做错了什么,从视图模型中,我尝试从用户{**Tousername 和 messagebody }中获取 #ToUserName** 正确发送,而当我调试时控制器中的#Body为空。我有以下 Jquery 代码:

$("#SendMessage").click(function () {
        var message = GrabMessage();

        var jsonData = JSON.stringify(message, null, 2);

        $.ajax({
            url: '@Url.Content("~/Message/Compose/")',
            type: 'POST',
            data: jsonData,
            datatype: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function () {
                $('#default_message').append("message sent ");
                switchToSentMessagesTab();
            },
            error: function (request, status, err) {
                alert(status);
                alert(err);
            }
        });

        return false;
    });

    function switchToSentMessagesTab() {
        $('a[href="#default_message"]').click();
    }


    function GrabMessage() {
        var touser = $("#ToUserName").val();
        var text = $("#Body").val();

        var result =
        {
            Body: text,
            ToUserName: touser

        };

        return result;
    }

});

和剃须刀视图:

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

    <div class="editor-label">
        @Html.LabelFor(model => model.ToUserName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.ToUserName, new { @class ="autocomplete"})
        @Html.ValidationMessageFor(model => model.ToUserName)
    </div>

    <div class="editor-field">
        @Html.EditorFor(model => model.Body)
        @Html.ValidationMessageFor(model => model.Body)
    </div>

    <p>
        <input id="SendMessage" type="submit" value="Send" />
    </p>

和控制器动作:

  [HttpPost]
    public ActionResult Compose(PrivateMessageViewModel m) 
    {
        if (User.Identity.IsAuthenticated )
        {
            if (ModelState.IsValid)
            {
                var ToUserName = users.Profiles.First(x => x.UserName == m.ToUserName);
                PrivateMessage message = new PrivateMessage
                {
                    //do some stuff here:                   

                };
                db.SendMessage(message);

                return RedirectToAction(//Some view here...)
            }
        }

        return PartialView(m);
    }
4

0 回答 0