使用Ajax将整个模型发布回控制器 [英] Posting entire model back to controller using ajax

查看:89
本文介绍了使用Ajax将整个模型发布回控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是ASP.NET MVC和Web技术的初学者. 现在我陷入了困境.我有一个创建用户页面.当管理员用户想要添加新用户时,他将被重定向到创建具有空数据类的用户页面.在该页面中,数据类已填充.现在,我想使用POST方法将该模型的数据返回给控制器.

I am a beginner in asp.net mvc and web technologies. Now I am stuck at some point. I have a create user page. When admin user wants to add a new user, he is redirected to create user page with an empty data class. In that page, the data class is filled up. Now I want to return that model's data back to the controller using a POST method.

我想要实现的是将整个模型作为JSON对象直接发布回控制器,并且始终为空.

What I am trying to achieve is to directly post the entire model as a JSON object back to the controller and it is always null.

在创建新用户时,单击:

[HttpGet]
public ActionResult CreateUser()
{
    var newUser = new User();
    return View(newUser);
}

我的CreateUser视图代码:

@model WebApplication7.Models.User
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>CreateUser</title>
    <h2>Create new user</h2>
</head>
<body>
    <div>
        <table>
            <tr>
                <td>Username : </td>
                <td>
                    @Html.TextBoxFor(model => model.userName, new { @class = "", id = "txtUsername", @maxlength = 6 })
                </td>
            </tr>

            <tr>
                <td>Password : </td>
                <td>
                    @Html.TextBoxFor(model => model.passWord, new { @class = "", id = "txtUsername", @maxlength = 6 })
                </td>
            </tr>

            <tr>
                <td>First Name : </td>
                <td>
                    @Html.TextBoxFor(model => model.firstName, new { @class = "", id = "txtUsername", @maxlength = 6 })
                </td>
            </tr>

            <tr>
                <td>Last Name : </td>
                <td>
                    @Html.TextBoxFor(model => model.lastName, new { @class = "", id = "txtUsername", @maxlength = 6 })
                </td>
            </tr>

            <tr>
                <td>Display name : </td>
                <td>
                    @Html.TextBoxFor(model => model.displayName, new { @class = "", id = "txtUsername", @maxlength = 6 })
                </td>
            </tr>

            <tr>
                <td>Email : </td>
                <td>
                    @Html.TextBoxFor(model => model.emailID, new { @class = "", id = "txtUsername", @maxlength = 6 })
                </td>
            </tr>    
            <tr>
                <td>
                <input type="button" name="btnClear" value="Submit" class="btn-Clear" onclick="Submit()" />
                    </td>
            </tr>
        </table>
    </div>
</body>
</html>

提交功能代​​码:

<script>
    function Submit() {
        $.ajax({
            type: "POST",
            url: "/UserManagement/SubmitNewUserData",
            data: JSON.stringify({ userData: model }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                ServiceSucceeded(msg);
            },
            error: function () {
                return "error";
            }
        });
    }
</script>

我的控制器代码:

[HttpPost]
public JsonResult SubmitNewUserData(User userData)
{
    if (userData != null)
    {

    }
    return Json(true);
}

此处的userData始终为null.请帮助我将该模型发回到该控制器.谢谢.

The userData here is null always. Please help me to post back that model to this controller. Thank you.

推荐答案

您尚未说明model的值是什么,但是为了起作用,它需要

You have not indicated what the value of model is, but in order to work, it would need to

var model = {
    userName: $('#userName').val(),
    passWord: $('#passWord').val(),
    ... // etc for each property of User
};

假设您删除了所有new { id = "txtUsername" }属性,这些属性会生成无效的(重复的)名称属性.

assuming you remove all you new { id = "txtUsername" } attributes which is generating invalid (duplicate) name attributes.

一个简单得多的解决方案是将所有窗体控件包装在<form>标记中,然后使用.serialize();正确序列化所有窗体控件.该脚本将是

A far easier solution is to wrap all you form controls in a <form> tag and then use .serialize(); to correctly serialize all your form controls. The script would then be

$.ajax({
    type: "POST",
    url: '@Url.Action("SubmitNewUserData", "UserManagement")', // always use Url.Action() to generate your url's
    data: $('form').serialize;
    dataType: "json",
    success: function (msg) {
        ServiceSucceeded(msg);
    },
    error: function () {
        return "error";
    }
});
return false; // cancel the default submit

要进一步改善这一点,请删除您的onclick="Submit()"并使用 Unobtrusive Javascript处理.submit()事件/a>

To improve this further, remove your onclick="Submit()" and handle the .submit() event using Unobtrusive Javascript

$('form').submit(function() {
    if (!$(this).valid()) {
        return;
    }
    $.ajax({
       ....
    });
    return false;
});

if (!$(this).valid()) {将允许您处理客户端验证,您应该通过包括@Html.ValidationMessageFor(..)帮助器以及相关的jquery.validate.jsjquery.validate.unobtrusive.js脚本,并在模型属性中添加验证属性来进行客户端验证.您可以同时进行客户端和服务器端验证.

The if (!$(this).valid()) { will allow you to handle client side validation, which you should be doing by including @Html.ValidationMessageFor(..) helpers and including the relevant jquery.validate.js and jquery.validate.unobtrusive.js scripts, and adding validation attributes to your model properties so that you get both client and server side validation.

侧面说明:应使用@Html.PasswordFor()生成密码字段.还不清楚为什么您使用ajax而不是标准提交(为什么要让用户停留在同一页面上并再次对其进行编辑?

Side note: A password field should be generate with @Html.PasswordFor(). Its also unclear why your using ajax rather than a standard submit (why would you want the user to stay on the same page and edit it again?

这篇关于使用Ajax将整个模型发布回控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆