如何在jQuery中将序列化表单数据发布到URL?

时间:2017-11-14 14:38:46

标签: c# jquery xml serialization asp.net-mvc-5

我有一个ASP.NET Web应用程序,它基本上由一个包含许多字段的表单组成,这些字段必须序列化为XML。服务器期望有一个预定的结构;我已经设置了我的类(模型)来反映这种结构。我使用[Serializable]属性修饰了模型类,以便保留XML结构。我测试了序列化;它运作正常。以下是我测试它的方法:

[HttpPost]
        public XmlResult Sample2(Transmission t)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    XmlResult xrs = new XmlResult(t);
                    xrs.ExecuteResult(ControllerContext);
                    return xrs;
                }
                else
                {
                    return null;
                }
            }
            catch
            {
                return null;
            }
        }

以下是我正在使用的XmlResult课程:

public class XmlResult : ActionResult
    {
        private object objectToSerialize;

        /// <summary>
        /// Initializes a new instance of the <see cref="XmlResult"/> class.
        /// </summary>
        /// <param name="objectToSerialize">The object to serialize to XML.</param>
        public XmlResult(object objectToSerialize)
        {
            this.objectToSerialize = objectToSerialize;
        }

        /// <summary>
        /// Gets the object to be serialized to XML.
        /// </summary>
        public object ObjectToSerialize
        {
            get { return objectToSerialize; }
        }

        /// <summary>
        /// Serializes the object that was passed into the constructor to XML and writes the corresponding XML to the result stream.
        /// </summary>
        /// <param name="context">The controller context for the current request.</param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (objectToSerialize != null)
            {
                context.HttpContext.Response.Clear();
                var xs = new System.Xml.Serialization.XmlSerializer(objectToSerialize.GetType());
                context.HttpContext.Response.ContentType = "xml";
                xs.Serialize(context.HttpContext.Response.Output, this.objectToSerialize);
            }
        }
    }

既然我知道数据是以正确的XML格式序列化的,那么如何使用jQuery将这些数据发布到服务器?请注意,我通过HTTPPOST请求将XML数据发送到客户的URL。

0 个答案:

没有答案