[英]How to execute an action link by passing an object as parameter in Asp.Net MVC 4?
I would like to execute an action by passing an object as a parameter. 我想通过传递一个对象作为参数来执行一个动作。 To do that I have serialized that object to a Json string then converted that string into Hex string, passed that Hex string as parameter in the action link.
为此,我已将该对象序列化为Json字符串,然后将该字符串转换为Hex字符串,并将该Hex字符串作为参数传递给action链接。
I have an object like this, 我有一个这样的东西,
Product prodObject = new Product { Categories = new Category { CategoryName = "Stationary" }, ProductName = "Book", Price = 250 };
Serialized above object to Json string like this, 这样将上面的对象序列化为Json字符串,
var jsontString = JsonConvert.SerializeObject(prodObject);
I have converted above Json String into Hex string using below code. 我已经使用以下代码将上面的Json String转换为Hex字符串。
public string ConvertStringtoHex(string encodeMe, System.Text.Encoding encoding)
{
Byte[] stringBytes = encoding.GetBytes(encodeMe);
StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
foreach (byte b in stringBytes)
{
sbBytes.AppendFormat("{0:X2}", b);
}
return sbBytes.ToString();
}
In my action result return like below, 在我的动作结果返回如下
string hexString = ConvertStringtoHex(jsontString, System.Text.Encoding.Unicode);
return JavaScript(string.Format("document.location = '{0}';", Url.Action("Checkout", "PurchaseModule", new { pid= hexString })));
Again I have converted that Hex string to Json string at the ActionResult Post method then I tried to convert Json string to my original object. 再次在ActionResult Post方法中将十六进制字符串转换为Json字符串,然后尝试将Json字符串转换为原始对象。
string MyString = ConvertHextoString(pid, System.Text.Encoding.Unicode);
Converted Hex string into Json string using below code, 使用以下代码将十六进制字符串转换为Json字符串,
public static string ConvertHextoString(string decodeMe, System.Text.Encoding encoding)
{
int numberChars = decodeMe.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(decodeMe.Substring(i, 2), 16);
}
return encoding.GetString(bytes);
}
De serialized string to Json String like below, 如下所示将序列化的字符串反序列化为Json String,
var JsonString = JsonConvert.DeserializeObject(MyString);
I am getting error at the below line code, 我在下面的代码行中遇到错误,
Product prodObject = (Product)JsonString;
Here I am getting an error like below. 在这里,我收到如下错误。
Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Product'.
Does anyone know how to solve this issue? 有谁知道如何解决这个问题?
尝试这个:
Product prodObject = JsonConvert.DeserializeObject<Product>(MyString);
Adding comment as answer: 添加评论作为答案:
Deserialise directly into the correct type: 直接反序列化为正确的类型:
var prodObject = JsonConvert.DeserializeObject<Product>(MyString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.