【问题标题】:Using jquery ajax, how do you post an object containing a list other objects使用 jquery ajax,如何发布包含其他对象列表的对象
【发布时间】:2014-04-24 06:45:25
【问题描述】:

鉴于这些 C# 对象

class foo 
{
    int fooId {get; set;}
    string fooName {get;set;}
    List<bar> bars {get; set;}
}

class bar
{
    int barId {get; set;}
    string barName {get;set;}
}

和一个 WebApi 方法

[HttpPost]
public HttpResponseMessage AddFooBar(foo model)
{
    //...
}

假设我们有一个用户输入 fooName 和 bar 项目列表的表单,那么从表单中序列化数据并将其提交给 WebApi 方法的最佳方法是什么?

【问题讨论】:

    标签: c# jquery ajax asp.net-web-api


    【解决方案1】:

    我强烈建议使用

    创建一个哑视图
    <form id="f">
    @Html.TextBoxFor(x=>x.foo);
    @for(var i = 0; i<Model.foo.bars.Length; i++){
        @Html.TextBoxFor(x=>x.foo.bars[i]);
    }
    </form>
    
    $(document).ready(function(){
        console.log($('#f').serialize());
    });
    

    因此您可以看到预期的结构。然后你可以按照你的意愿填写你的 JSON

    【讨论】:

    • 多个表单不起作用,因为这不是 asp.net mvc 而是带有 webapi webservices 的 asp.net webforms 应用程序。我正在寻找一种单一的 ajax 方法来发布 foo 和条形列表,以及一种单一的 webapi 方法来从浏览器接收您的答案未解决的数据。
    【解决方案2】:

    我找不到在一个 ajax 调用和一个 WebApi 控制器操作中发布 foo 和条形列表的方法。我以两个 ajax 帖子和两个控制器操作结束。两次而不是一次,但它有效。以下是我的解决方案,以防任何人发现它有用。

    在 html 方面,我为表单使用了两个 div,因为这是 Asp.net webforms,这意味着我们仅限于一种表单。

    <div id="foo-form">
        <input type="text" name="fooName" value="" />
        <button type="button" class="btn-cancel">Cancel</button>
        <button type="button" class="btn-submit">Submit</button>
    </div>
    
    <div id="bar-form">
        <input type="text" class="foobar" value="" />
        <input type="text" class="foobar" value="" />
        <input type="text" class="foobar" value="" />
        <input type="text" class="foobar" value="" />
    </div>
    

    Javascript 端(使用 Jquery ajax)

    $("#foo-form .btn-submit").click(function (e) {
        e.preventDefault();
        fooBar.saveFoo();
    });
    
    var fooBar = new function () {
    
        //this posts foo
        this.saveFoo = function () {
            // serialize the form
            var serializedData = $("#foo-form :input").serialize();
    
            $.ajax({
                type: "POST",
                url: "/myapp/api/FooBar/AddFoo",
                data: serializedData,
                cache: false
            }).done(function (data) {
                if (data["Status"] === 'success') {
                    //pass the id to the saveBars function
                    fooBar.saveBars(data["Id"])
                }
                else {
                    //handle logic error
                }
            }).fail(function (xhr, textStatus, errorThrown) {
                //handle ajax error
            }).always(function () {
                //something to do always
            });
        }
    
    
        //this posts bars
        this.saveBars = function (fooId) {
    
            //save all bars in array
            var arrBars = [];
            $('#bar-form .foobar').each(function () {
                arrBars.push(
                        {
                            "fooId": fooId,
                            "fooName": $(this).val()
                        }
                    );
            });
    
            $.ajax({
                type: "POST",
                url: "/myapp/api/FooBar/AddBars",
                data: JSON.stringify(arrBars),
                cache: false,
                contentType: "application/json; charset=utf-8"
            }).done(function (data) {
                if (data["Status"] === 'success') {
                    //show success message
                }
                else {
                    //handle logic error
                }
            }).fail(function (xhr, textStatus, errorThrown) {
                //handle ajax error
            }).always(function () {
                //something to do always
            });
        }
    }
    

    现在在服务器端 webapi 控制器 C# 代码

    [HttpPost]
    public HttpResponseMessage AddFoo(Foo model)
    {
        try
        {
            //validate
            if (!ModelState.IsValid)
                return Request.CreateResponse(HttpStatusCode.OK, new { Status = "error", Message = "Error in foo"});
            //save foo
            var db = new FooBarDB();
            var id = db.AddFoo(model);
            //return new fooId
            return Request.CreateResponse(HttpStatusCode.OK, new { Status = "success", Id = id });
        }
        catch (Exception ex)
        {                
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
        }
    }
    
    [HttpPost]
    public HttpResponseMessage AddBars(List<Bar> bars)
    {
        try
        {
            //validate bars
            if (!this.ValidateBars(bars))
                return Request.CreateResponse(HttpStatusCode.OK, new { Status = "error", Message = "Errors in bars"});
            //save bars
            var db = new FooBarDB();
            db.AddBars(bars);
            //show success
            return Request.CreateResponse(HttpStatusCode.OK, new { Status = "success"});
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
        }
    }
    
    private bool ValidateBars(List<Bar> bars)
    {
        //logic to validate bars
    }
    

    【讨论】:

    • 现在我更喜欢AngularJs,因为它使上述内容变得微不足道。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多