您好,我想将一个对象传递到我的 View 并在 JavaScript 中使用它。我创建了这个模型
namespace WebApplication1.Models
{
public class OpenlayerLayer
{
public OpenlayerLayer(string Layers,string name,string url,string style,Boolean isqueryable,string projection,string maxEx)
{
LAYERS = Layers;
Name = name;
URL = url;
STYLES = style;
queryable = isqueryable;
this.projection = projection;
maxExtent = maxEx;
}
public string LAYERS { get; set; }
public string Name { get; set; }
public string URL { get; set; }
public string STYLES { get; set; }
public Boolean queryable { get; set; }
public string projection { get; set; }
public string maxExtent { get; set; }
}
}
我在 Controller 中使用了这个方法
public string getLayerlist()
{
OpenlayerLayer ol = new OpenlayerLayer("Test: GParcel", "Parcels", "http://127.0.0.1:8080/geoserver/test/wms", "", true, "EPSG:900913", "5725524.327803587, 3835467.5859751734, 5729564.058979791, 3841404.792330884");
var json = JsonConvert.SerializeObject(ol);
return json;
}
好吧,我在我的观点中使用了这个
$(selector).getJSON('getLayerlist', data, loadopenlayers(data, status))
这是'loadopenlayers'方法
function loadopenlayers(result,status) {
alert("Seems works fine");
var layer = JSON && JSON.parse(result) || $.parseJSON(result);
var wms2 = new OpenLayers.Layer.WMS(
layer.name, layer.URL,
{
LAYERS: layer.LAYERS,
STYLES: layer.STYLES,
format: format,
},
{
buffer: 0,
displayOutsideMaxExtent: true,
isBaseLayer: true,
projection: new OpenLayers.Projection(layer.projection),
minResolution: null,
maxResolution: 48,
numZoomLevels: 32,
maxScale: null,
minScale: 1271428,
maxExtent: new OpenLayers.Bounds(layer.maxExtent),
minExtent: null,
displayProjection: new OpenLayers.Projection("EPSG:4326"),
}
);
}
所以它必须工作,然后在 JavaScript 代码中调用 loadopenlayers
,对吗?
现在我遇到了一个问题,如何在 loadopenlayers
getLayerlist
的结果
我的方法是否适合在 View 中的模型和 JavaScript 之间进行通信? 事实上,我有大量的 JavaScript 代码必须使用模型参数进行自定义,我想要一个一致性和标准的方法来做到这一点 非常感谢
最佳答案
最好使用 jquery ajax 调用,例如:
$.ajax({
type: "POST",
url: '/ControllerName/getLayerlist',
// data: data,send data to controller from here
dataType: 'json',
//processData: false,
success: function (msg) {
//your json data will be available in msg
//here you can also call loadopenplayers() method
},error: function (error) {
console.log(error.responseText);
}
});
而你的 Controller 方法看起来像
[HttpPost]
public JsonResult getLayerlist(string data)
{
OpenlayerLayer ol = new OpenlayerLayer("Test: GParcel", "Parcels", "http://127.0.0.1:8080/geoserver/test/wms", "", true, "EPSG:900913", "5725524.327803587, 3835467.5859751734, 5729564.058979791, 3841404.792330884");
return Json(ol , JsonRequestBehavior.AllowGet);//automatically converts to Json
}
关于javascript - 使用 json 和 Ajax 将对象传递给 MVC View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38177512/