KnockOutJs对象不张贴 [英] KnockOutJs object not posting

查看:119
本文介绍了KnockOutJs对象不张贴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过KnockOutJs采样工作,我有与MVC3张贴的一些问题。我的示例使用一整页的回发时,正确的职位。当我尝试使用jQuery的一个阿贾克斯后保存,我可以看到张贴在使用Firebug NET观众是:

{礼物:[{GiftId:0,标题:悲,价格:3}]}

当我查看了ModelBinder的MVC3中的ControllerContext,表单参数为空并且json不绑定。任何想法发生了什么?

我已经尝试了多种配置,但这里是jQuery的发帖code(目前硬coded到一个静态值):

...

  $阿贾克斯({
        网址:/首页/ PartialUpdate
        输入:POST,
        缓存:假的,
        数据:{礼物:[{GiftId:0,标题:悲,价格:3}]}',//ko.toJSON({礼物:this.gifts})
        数据类型:JSON,
        的contentType:应用/ JSON;,
        成功:函数(结果){
            警报(结果);
            VAR数据= ko.utils.parseJson(结果);
            this.gifts = ko.observableArray(数据);
        },
        错误:功能(XHR,ERR){
            警报(readyState的:+ xhr.readyState +\\ n状态:+ xhr.status);
            警报(responseText的:+ xhr.responseText);
        }
        });


编辑:这里是行动MVC3 code代表阿贾克斯更新code

  [HttpPost]
公共JsonResult PartialUpdate([FromJson]的IEnumerable<礼品GT;礼品)
{
    礼品赠品=?新的List<礼品GT;();
    使用(VAR上下文=新KnockOutContext())
    {
        //添加记录,如果未在DB
        的foreach(在礼品赠送VAR)
        {
            context.Entry(礼品).STATE =(gift.GiftId == 0)? EntityState.Added:EntityState.Modified;
        }        //如果不是在视图模型删除记录
        的foreach(在context.Gifts VAR dbGift)
        {
            如果(gifts.SingleOrDefault(C => c.GiftId == dbGift.GiftId)== NULL)
                context.Gifts.Remove(dbGift);
        }
        context.SaveChanges();
    }
    返回GetGifts_Json();
}

和全回传code,在工程(史蒂夫·桑德森的榜样
http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/)

  [HttpPost]
公众的ActionResult指数([FromJson]的IEnumerable<礼品GT;礼品)
{
    SaveGifts(礼品);
    返回RedirectToAction(「指数」);
}

使用

这个自定义模型粘结剂:

 公共类FromJsonAttribute:CustomModelBinderAttribute
        {
            私人只读静态的JavaScriptSerializer串=新的JavaScriptSerializer();            公众覆盖IModelBinder GetBinder()
            {
                返回新JsonModelBinder();
            }            私有类JsonModelBinder:IModelBinder
            {
                公共对象BindModel(ControllerContext controllerContext,ModelBindingContext的BindingContext)
                {
                    VAR字符串化= controllerContext.HttpContext.Request [bindingContext.ModelName]
                    如果(string.IsNullOrEmpty(字符串化))
                        返回null;
                    返回serializer.Deserialize(字符串化,bindingContext.ModelType);
                }
            }
        }


解决方案

我的猜测是,你开始与史蒂夫的下载,这是使用MVC2。 MVC2没有足够的<一个href=\"http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx\"相对=nofollow> JsonValueProvider 通过默认注册。在 [FromJson] 属性旨在与已通过ko.utils.postJson(完全回发)提交的URL恩codeD JSON工作。通过AJAX使用正确的内容类型(MVC3)发布JSON时,这是没有必要的。

那么,做最简单的事情就是你的项目升级到MVC 3(省事这里),并移除部分更新了 [FromJson] 属性。

工作拷贝这里

另外一个真正次要的事情:你的静态数据目前是无效的JSON('{礼物:[{GiftId:0,标题:悲,价格:3}] } )。 礼品将需要礼物

I am working through a KnockOutJs Sample and am having some posting problems with MVC3. My sample correctly posts when using a full page postback. When I try to save using an jQuery Ajax post, I can see the Post in the using Firebug NET viewer to be:

{ gifts:[{"GiftId":0,"Title":"sad","Price":3}] }

When I view the ControllerContext in the ModelBinder in MVC3, the form parameters are empty and the json does not bind. Any ideas as to what is happening?

I have tried a number of configurations but here is the jQuery posting code (currently hard-coded to a static value):

...

            $.ajax({
        url: "/Home/PartialUpdate", 
        type: 'POST', 
        cache: false,
        data:   '{ gifts:[{"GiftId":0,"Title":"sad","Price":3}] }', //ko.toJSON({ gifts: this.gifts }),   
        dataType: 'json' ,
        contentType: "application/json;",
        success: function(result){
            alert(result);
            var data = ko.utils.parseJson(result); 
            this.gifts =  ko.observableArray(data) ;
        },
        error:function(xhr,err){ 
            alert("readyState: " + xhr.readyState+"\nstatus: "+xhr.status); 
            alert("responseText: " + xhr.responseText);
        }
        });


Edit: Here is the MVC3 action code for the Ajax update code

[HttpPost]
public JsonResult PartialUpdate ([FromJson] IEnumerable<Gift> gifts)
{
    gifts = gifts ?? new List<Gift>();
    using (var context = new KnockOutContext())
    {
        // Add record if not in DB
        foreach (var gift in gifts )
        {
            context.Entry(gift).State = (gift.GiftId == 0) ? EntityState.Added : EntityState.Modified;
        }

        // Delete records if not in ViewModel
        foreach (var dbGift in context.Gifts)
        {
            if (gifts.SingleOrDefault(c => c.GiftId == dbGift.GiftId) == null)
                context.Gifts.Remove(dbGift);
        }
        context.SaveChanges();
    }
    return GetGifts_Json();
}

And the full postback code that works (from Steve Sanderson's example at http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/)

[HttpPost]
public ActionResult Index([FromJson] IEnumerable<Gift> gifts)
{
    SaveGifts(gifts);
    return RedirectToAction("Index");
}

using this custom model binder:

        public class FromJsonAttribute : CustomModelBinderAttribute
        {
            private readonly static JavaScriptSerializer serializer = new JavaScriptSerializer();

            public override IModelBinder GetBinder()
            {
                return new JsonModelBinder();
            }

            private class JsonModelBinder : IModelBinder
            {
                public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
                {
                    var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
                    if (string.IsNullOrEmpty(stringified))
                        return null;
                    return serializer.Deserialize(stringified, bindingContext.ModelType);
                }
            }
        }

解决方案

My guess is that you started with Steve's download, which is using MVC2. MVC2 did not have the JsonValueProvider registered by default. The [FromJson] attribute was intended to work with URL-encoded JSON that was submitted via ko.utils.postJson (full postback). This is not necessary when posting JSON via AJAX with the correct content-type (in MVC3).

So, the easiest thing to do is upgrade your project to MVC 3 (easy way here) and remove the [FromJson] attribute from your partial update.

Working copy here.

One other really minor thing: your static data is currently invalid JSON ('{ gifts:[{"GiftId":0,"Title":"sad","Price":3}] }'). gifts would need to be "gifts"

这篇关于KnockOutJs对象不张贴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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