3月 30, 2014

MVC Jquery傳checkbox已勾選的物件陣列回control

首先在View中加入webgrid並且放入checkbox
<div id="gridContent">
@grid.GetHtml(
columns: grid.Columns(
grid.Column("id", "id", format: @<input class="select" id="assignChkBx" name="assignChkBx" type="checkbox" value="@item.id"/>),
grid.Column("item", "item"),
grid.Column("name", "改字", style: "description")
)) 
</div>

Jquery的寫法如下
$("#Button2").click(function () {
            var str=[];
            $("input:[name='assignChkBx'][checked]").each(function () {      
                str.push($(this).val());
            });
            $.post("@Url.Content("~/store/bgg")",
                   
                    {user:JSON.stringify(str)  },
                    function (res) {
                        alert(res);
                    });
        });

接著回到controll
由於物件陣列的回傳會因為jquery的處理而接收不到
因此必須在controll底下加入一個處理方法
 /// <summary>
    /// FromJsonAttribute
    /// 用在透過javascript 傳送json格式資料到controller時使用
    /// </summary>
    public class FromJsonAttribute : CustomModelBinderAttribute
    {
        /// <summary>
        /// JavaScriptSerializer
        /// </summary>
        private readonly static JavaScriptSerializer serializer = new JavaScriptSerializer();

        /// <summary>
        /// GetBinder
        /// </summary>
        /// <returns>Binder</returns>
        public override IModelBinder GetBinder()
        {
            return new JsonModelBinder();
        }

        /// <summary>
        /// JsonModelBinder
        /// </summary>
        private class JsonModelBinder : IModelBinder
        {
            /// <summary>
            /// BindModel
            /// </summary>
            ///<param name="controllerContext">controllerContext
            ///<param name="bindingContext">bindingContext
            /// <returns>object</returns>
            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);
            }
        }
    }


然後接著是controll的部分
string tt;
        public ActionResult bgg([FromJson]List<int> user)
        {
            
            
            if (user != null)
            {
                foreach(var item in user){
                    tt += item.ToString();
                }
            }
                return Content(tt);
            
        }

如此一來就能將被勾選的Value正確傳給controll~!

沒有留言: