我有一个像这样的JSON数组:
theFormData = {"FormNodeID":142365,"SubmissionMethod":"Desktop","ConfirmationEmailID":"142371","FirstName":"Solomon","LastName":"Closson","EmailAddress":"myemail@testing.com","Company":"TIF","JobTitle":"Web Developer"}
FormNodeID
,SubmissionMethod
和ConfirmationEmailID
将始终相同,但FirstName
,LastName
,EmailAddress
,{{1并且Company
正在使用javascript作为字符串填充到JSON中,该字符串将根据管理员放入Label中的值进行更改,并使用正则表达式删除特殊字符和空格。
所以,我有代码将其填充到另一个变量中,称为JobTitle
,而不是像这样添加这些JSON对象:
theProperty
其中value等于输入值。问题是,我需要能够将此JSON变量传输到ASP.NET C#类文件theFormData[theProperty] = value;
,并从JSON对象动态构建类属性。这可能吗?
现在正使用以下代码将其发送给Handler:
.cs
MakeRequest及其依赖函数如下所示:
var formdata = 'formdata=' + encodeURIComponent(Sys.Serialization.JavaScriptSerializer.serialize(theFormData));
MakeRequest('/handlers/formshandler.ashx?f=formcontrol&r=' + Math.random(), 'POST', formdata, SaveComplete, null);
将其传递给位于处理程序/ formhandler.ashx
中的表单处理程序在这个文件中,我检查f的请求,然后抓住发布的function MakeRequest (url, verb, data, func, obj) {
try {
var TheRequest = new Sys.Net.WebRequest();
TheRequest.set_url(url);
TheRequest.set_httpVerb(verb);
if (data) {
TheRequest.set_body(data);
}
TheRequest.set_userContext(new RequestParamsNew(func, obj));
TheRequest.add_completed(MakeRequestComplete);
TheRequest.invoke();
return TheRequest;
}
catch (error) {
if (func) func('Communication Error');
}
}
function MakeRequestComplete (executer, eventArgs)
{
var TheParams = executer.get_webRequest().get_userContext();
if (executer.get_responseAvailable())
{
TheParams.responseData = executer.get_responseData().replace(/\u2028/g, '');
}
else
{
TheParams.responseData = null;
}
if (TheParams.func) TheParams.func(TheParams);
}
function RequestParamsNew(afunc, obj)
{
this.func = afunc;
this.responseData = null;
this.obj = obj;
this.Error = null;
}
,如下所示:
formdata
所以CustomForm是一个Class文件,我需要能够完全填充formdata JSON变量的属性。这似乎并没有这样做。它似乎能够获取值,但我必须在。CustomForm theCustomForm = new JavaScriptSerializer().Deserialize<CustomForm>(_Context.Request["formdata"]);
文件中手动输入.cs文件中设置公共属性。但相反,我需要它自动创建基于JSON的属性,因为不同形式的属性很可能是不同的。
这怎么可能呢?
修改 的
好的,现在根据对此的评论使用CustomForm.cs
而不是类。
在处理程序中,现在使用此代码:
Dictionary<string, string>
只是测试一下是否会返回任何List<string> theErrors = new List<string>();
Dictionary<string, string> theCustomForm = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(_Context.Request["formdata"]);
foreach (KeyValuePair<string, string> pair in theCustomForm)
{
theErrors.Add(pair.Key + " = " + pair.Value);
}
_Context.Response.Write(new
{
Valid = theErrors.Count == 0,
Errors = theErrors,
Message = "Form Submitted"
}.ToJson());
。我的SaveComplete函数如下所示:
Errors
但是我得到以下错误:
function SaveComplete(params) {
if (params.responseData) {
var theItems = eval(Sys.Serialization.JavaScriptSerializer.deserialize(params.responseData, false));
if (theItems.Valid) {
// Redirect somewhere...
document.location.href = "http://www.google.com";
}
else {
$.each(theItems.Errors, function (idx, error) {
Console.Log(error);
});
}
}
}
如果我将Sys.ArgumentException: Sys.ArgumentException: Cannot deserialize. The data does not correspond to valid JSON.
Parameter name: data
功能中的theItems
部分更改为:
SaveComplete
它会发出以下警告(500页错误):
var theItems = params.responseData;
alert(theItems);
这来自网站root中的500.htm文件。 web.config文件中是否存在需要为此而完成的内容,或许我可能会遗漏?
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<title>PHL</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="width=1024" />
<meta charset="utf-8" />
<link rel="shortcut icon" href="/media/1606636/homestead_favicon.ico" type="image/x-icon" />
<link rel="stylesheet" href="/scripts/jquery-select2/select2.css" />
<!-- <link rel="stylesheet" href="styles/bootstrap.css" /> -->
<link rel="stylesheet" href="/styles/datepicker.css" />
<link rel="stylesheet" href="/styles/styles.css" />
<script type="text/javascript" src="//use.typekit.net/qrs7pfm.js"></script>
<script type="text/javascript"> try { Typekit.load(); } catch (e) { }</script>
<script type="text/javascript" src="/scripts/BaseUI.js"></script>
</head>
<body>
<div class="var-nav" style="display: none;"></div>
<div id="Container" class="secondary">
<!-- Header -->
<div class="header-elements clearfix">
<div class="header-row row">
<header class="header container">
<div class="main-nav nav-small">
<div class="clearfix">
<nav>
<ul class="nav-buttons">
<li class="phl-logo"><a href="/">PHL</a></li>
</li>
</ul>
</nav>
</div>
</div>
</header>
</div>
<div id="call-phl">1-800-CALL-PHL</div>
</div>
<!-- .Header -->
<div id="hero-slideshow" class="hero-slideshow">
<div class="slides">
<div class="slide">
<img src="/images/SAMPLE_slide-grad-bg.jpg" alt="" />
</div>
</div>
</div>
<div class="page tertiary bg_pattern">
<div class="">
<div class="row-inner breadcrumbs-row">
<ul class="breadcrumbs clearfix">
<li><a href="/">Home</a></li>
<li>Error 500</li>
</ul>
</div>
<div class="row-inner bg_pattern">
<h1>Error 500: Internal Server Error</h1>
<!-- Right Rail Column -->
<div class="right-rail clearfix">
<div class="body article-body">
<div class="article container">
<p>The server was unable to send the html document to you due to an internal (server software) error.</p>
<p>If the issue persists, contact <a href="#">webmaster@discoverPHL.com</a></p>
</div>
</div>
<div class="rail">
</div>
</div>
<!-- Right Rail Column -->
</div>
</div>
</div>
</div>
<!-- .Footer -->
</div>
</body>
</html>
返回JSON就好了,所以它必须与它反序列化的方式一致吗?
答案 0 :(得分:1)
问题通过以下方式解决:
public void SubmitCustomForm()
{
List<string> theErrors = new List<string>();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var dict = serializer.Deserialize<Dictionary<string, string>>(_Context.Request["formdata"]);
foreach (KeyValuePair<string, string> pair in dict)
{
theErrors.Add(pair.Key + " = " + pair.Value);
}
_Context.Response.Write(new
{
Valid = theErrors.Count == 0,
Errors = theErrors,
Message = "Form Submitted"
}.ToJson());
}
此验证完全正确,没有错误。不知道为什么其他方法不起作用,但这个至少现在完善了,让我处理词典项目......