开发者

Deserialize jQuery Serialized Form

I'm trying to pass form inputs into a WebMethod and doing something. I used jQuery Serialize.

<script type="text/javascript">
        $.fn.serializeNoViewState = function () {
            return this.find("input,textarea,select,hidden")
               .not("[type=hidden][name^=__]")
               .serialize();
        }

        $(function () {
            $("#Button1").click(function (e) {
                var res = $("#myform").serializeNoViewState();
                var jsonText = JSON.stringify({ bject: res });
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/Test",
                    data: jsonText,
                    contentType: "application/json; charset=utf-8",
                    dataType: "jso开发者_如何学编程n",
                    success: function (msg) {
                    //    alert("asd");


                    },
                    error: AjaxFailed
                });
            });
        });
        function AjaxFailed(result) {
            alert("Failed");
        }  
    </script>

in target WebMethod I want to Deserialize that object I passed.

[WebMethod()]
public static bool test(string bject)
{
    JavaScriptSerializer JsTool = new JavaScriptSerializer();

}

I Tried to use Javascriptserilizer Class. but I did not succeed. now how can I use this Object? I want to use this way for using jQuery AJAX simpler(For example passing form inputs to a WebService and inserting that in Database). Due the action I want to do is this way right ? Welcome your Suggestions , tips .

Update:

how can I map the Serialized JS object to my C# entity object? Is this way is good Way ? or there are better way exist ? if yes please give me some information


I would recommend you working with strong types. So define a class that will contain all the necessary properties:

public class MyModel
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

and then have your web method take this object:

[WebMethod()]
public static bool test(MyModel bject)
{
    ...
}

The name of the properties must match the input field names you are serializing in the AJAX request.


May be you can try this:

JavaScriptSerializer JsTool = new JavaScriptSerializer();

var listOfObjs = JsTool.Deserialize<List<YourDataType>>(bject);

Hope it helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜