简体   繁体   English

如何在Javascript / Ajax中将多个值作为单个对象传递

[英]How to pass multiple values as single object in Javascript/Ajax

I'm new to javascript and MVC I'm working on a sample application containing a sign up page and I'm using ajax to done the process my current code is given below 我是javascript和MVC的新手我正在开发一个包含注册页面的示例应用程序,我正在使用ajax来完成这个过程,我现在的代码在下面给出

  function create() {
        var user_name = $("#txtUser").val();
        var pass = $("#txtPass").val();
        var email = $("#txtEmail").val();
        var phone = $("#txtPhone").val();
        var city = $("#txtCity").val();
        var state = $("#txtState").val();
        var zip = $("#txtZip").val();
        $.ajax({
            url: '/EmberNew/Home/Create',
            type: 'POST',
            data: { user_name: user_name, pass: pass,email:email,phone:phone,city:city,state:state,zip:zip },
            success: function (response) {
                alert("success");
            }
        });
        return false;
    }

and its working fine but I want to know that is there any way to pass these values as a single object like in C# forgive me if this question is too silly 并且它的工作正常,但我想知道有没有办法将这些值作为单个对象传递,就像在C#中一样,如果这个问题太傻了,请原谅我

serverside code 服务器端代码

[HttpPost]
public ActionResult Create(User user)
{
    UserDL newUser = new UserDL();
    newUser.SignUp(user);

    return Json(new { success = true });

}

and also I want to know is there any way to combine these values directly with my server side object 而且我想知道有没有办法将这些值直接与我的服务器端对象相结合

User.cs User.cs

public class User
{
    public virtual int ID { get; set; }
    public virtual string UserName { get; set; }
    public virtual string Password { get; set; }
    public virtual string EmailID { get; set; }
    public virtual int Phone { get; set; }
    public virtual string City { get; set; }
    public virtual string State { get; set; }
    public virtual int Zip { get; set; }

}

Try below code. 试试下面的代码。 Sore all variable in single object named data and pass it. 在单个对象命名数据中输出所有变量并传递它。

function create() {

        var data = {
            'UserName': $("#txtUser").val(),
            'Password': $("#txtPass").val(),
            'EmailID': $("#txtEmail").val(),
            'Phone': $("#txtPhone").val(),
            'City': $("#txtCity").val(),
            'State': $("#txtState").val(),
            'Zip': $("#txtZip").val()
        };
        $.ajax({
            url: '/EmberNew/Home/Create',
            type: 'POST',
            data: data ,
            success: function (response) {
                alert("success");
            }
        });
        return false;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM