我有ASP.Net MVC3应用程序。我的任务是从文件中读取点并显示它们。对于从文件读取点我使用DLL。我用javascript绘制它们。 这是我的代码:
// Controller
{
IntPtr lib = LoadLibrary("lib.dll");
// getting points from DLL. I get then as array of strings to serialise later
string[] points = new string[0];
GetArrayPointsAsStrings(points); // I get coordinates - [x1, y1, z1, x2, y2, z2, ..]
FreeLibrary(lib);
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
string serialized_points = serializer.Serialize(points);
return View(new MyModel(serialized_points));
}
// Model
public class MyModel
{
public string Points { get; private set; }
}
// View
@{
var m = Model;
var array_of_strings_points = m.Points;
}
// object from javascript
var js_obj = new js_obj();
var points_string = '@Html.Raw(@array_of_strings_points)';
js_obj.DrawPoints(points_string);
//js
//.. and here in DrawPoints() I parse the string of points and draw point
我的问题是:将所有序列化点从控制器传递给javascript是否可以这样做?可能有更好的方法将所有点传递给javascript?
谢谢, 振亚
答案 0 :(得分:2)
我的问题是:将所有序列化点传递给字符串是否可以 控制器以这种方式javascript?可能有更好的方式通过 所有指向javascript?
在您的模型上保留真实的CLR类型(string[]
)。您不需要在控制器中进行JSON序列化:
public class MyModel
{
public string[] Points { get; set; }
}
然后让控制器填充并将视图模型传递给视图:
string[] points = ...
MyModel model = new MyModel();
mode.Points = points;
return View(model);
最后在你看来:
@model MyModel
...
<script type="text/javascript">
var js_obj = new js_obj();
var points = @Html.Raw(Json.Encode(Model.Points));
js_obj.DrawPoints(points);
</script>
现在,如果您的js_obj.DrawPoints
期望JSON字符串作为参数而不是javascript数组
您可以像这样传递字符串:
@model MyModel
...
<script type="text/javascript">
var js_obj = new js_obj();
var points = @Html.Raw(Json.Encode(Model.Points));
js_obj.DrawPoints(JSON.stringify(points));
</script>