我有下一个C#代码:
public class Login
{
public string UserName { get; set; }
public string Password { get; set; }
public Login(string UserName, string Password)
{
this.UserName = UserName;
this.Password = Password;
}
}
protected const string JsonFunctionFormat = "function {0}(){{ {1}; }}";
protected const string JsonReturnFunctionFormat = "function {0}(){{return {1};}}";
public static void Fill(HtmlDocument Document, string FillerFunctionCode, Login LoginData)
{
if (Document != null)
{
HtmlElement dataElement = Document.CreateElement(OrganizationCardFiller.ScriptHtmlElementName);
IHTMLScriptElement domDataElement = (IHTMLScriptElement)dataElement.DomElement;
domDataElement.text = string.Format(LoginFiller.JsonReturnFunctionFormat, LoginFiller.GetLoginInfoFunctionName, LoginFiller.ConvertToJSon(LoginData));
//domDataElement.text += string.Format(LoginFiller.JsonFunctionFormat, LoginFiller.FillerFunctionName, FillerFunctionCode);
domDataElement.text += FillerFunctionCode;
HtmlElement headElement = Document.GetElementsByTagName(LoginFiller.BodyHtmlElementName)[0];
headElement.AppendChild(dataElement);
//Document.InvokeScript(LoginFiller.FillerFunctionName);
//Document.InvokeScript("FillLoginForm", new object[]{LoginFiller.ConvertToJSon(LoginData)});
//object[] args = { LoginFiller.ConvertToJSon(LoginData) };
//Document.InvokeScript("FillLoginForm", args);
Document.InvokeScript("FillLoginForm", new object[] { "{UserName:'user',Password:'pass'}" });
}
}
private static string ConvertToJSon(object ConvertingObject)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Serialize(ConvertingObject);
}
下一个JavaScript函数:
function objToString (obj) {
var str = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + '::' + obj[p] + '\n';
}
}
return str;
}
function FillLoginForm(login)
{
var userName = document.getElementById('ctl00_ctplhMain_Login1_UserName');
var password = document.getElementById('ctl00_ctplhMain_Login1_Password');
alert(objToString({test: 123, test2: '12345'}));
alert(objToString({""UserName"":""username"",""Password"":""veryHardPassword""}));
alert(typeof(login));
alert(login);
alert(objToString(login));
if(userName!=null)
{
userName.value = login.UserName;
}
if(password!=null)
{
password.value=login.Password;
}
}
"{test: 123, test2: '12345'}"
和"{""UserName"":""username"",""Password"":""veryHardPassword""}"
的提醒效果很好,但typeof(login)
返回“未知”,“登录” “objToString(login)” 返回空。如您所见,我尝试了不同的变体,但所有变量都返回Empty。我犯了什么错误,为什么登录参数不能通过正确的格式传递给JavaScript函数?