我的index.cshtml中有以下代码,其中正在创建FoursquareInfo对象。
@using WebMatrix.Data;
@using CanYouPay.Models.FoursquareAPI;
@{
FoursquareInfo fsInfo = new FoursquareInfo();
Checkins response = new Checkins();
Checkin checkins = new Checkin();
List<RootItem> items = new List<RootItem>();
RootItem item = new RootItem();
Venue venue = new Venue();
Location loc = new Location();
loc.lat = 51.19189444478925;
loc.lng = 4.664656084372357;
venue.location = loc;
item.venue = venue;
items.Add(item);
checkins.items = items;
response.checkins = checkins;
fsInfo.response = response;
}
我的 html 代码中有一个用于 index.cshtml 的 div,其中单击时会调用 updateMap(fourSquareInfo)
方法。
<div id="mapBtn" onclick="updateMap(@fsInfo)" class="btn btn-success btn-lg col-md-2 pull-right">Show Map!</div>
我的updateMap
函数是:
function updateMap(foursquareInfo) {
var uluru = { lat: 20, lng: 30 };
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
是的,出于测试目的,我不会对传递的 foursquareInfo
对象执行任何操作 - lat
和 long
值将被替换为当我可以修复 onClick
事件发生时收到的错误时,使用 foursquareInfo
:
CanYouPay 未在 HTMLDivElement.onclick 中定义
我的 html/razor/js 代码有什么问题?
最佳答案
根据我的评论:看起来您正在尝试将 C# 对象传递到您的 js 中 - 如果您查看该按钮上的源代码,它可能会是一些文本,包括 CanYouPay 并且您尚未将其定义为 js变量,它会抛出一个错误,你要么需要创建一个 js 对象并将你的 C# 对象值映射到它,要么传递一堆字符串
选项 1 创建一个与您的 c# 对象相匹配的 js 对象,并在您的 razor 中映射这些值:
<script>
// this needs to be in your razor before the onclick (so object is created before you use it)
var fsJSObject = new fsJSObject(); // this object should match your c# object
fsJSObject.StringValue = '@fsInfo.StringValue'; // this needs to be the final value - eg a string, int, date, etc - cannot be another object, otherwise you will get a similar mistake to above
fsJSObject.IntValue= @fsInfo.IntValue;
// pass fsJSObject into your onclick function
</script>
选项 2,将值直接传递到函数中
onclick="updateMap('@fsInfo.StringValue', @fsInfo.IntValue, '@fsInfo.AnotherStringValue')"
注意字符串值周围的引号
关于javascript - 单击时未定义 C# razor 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44130922/