问题
I'm trying to pass form inputs into a WebMethod and doing something. I used jQuery Serilize.
<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: "json",
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
回答1:
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.
回答2:
May be you can try this:
JavaScriptSerializer JsTool = new JavaScriptSerializer();
var listOfObjs = JsTool.Deserialize<List<YourDataType>>(bject);
Hope it helps!
来源:https://stackoverflow.com/questions/5587402/deserialize-jquery-serialized-form