我希望在访问的每个页面上更新用户的纬度和经度。为了不重复,我创建了一个基本控制器,在其中我还实现了 onActionExecuting,它允许该方法每次都在派生控制器的每个操作上运行,但我不知道如何传递纬度和经度参数,因为它们仅通过 Ajax 调用从浏览器传递。
public class BaseController : Controller
{
protected readonly UserManager<ApplicationUser> _userManager;
public BaseController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
UpdateLocation(latitude, longitude); //How do I pass these parameters from Ajax?
}
public void UpdateLocation(double latitude, double longitude)
{
var user = _userManager.GetUserAsync(User);
if (user != null)
{
user.Location = new Point(latitude, longitude) { SRID = 4326 };
await _userManager.UpdateAsync(user);
}
}
}
我将此脚本放置在布局中。它检索位置数据并将其发送到操作方法。
<script>
$(document).ready(function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else {
console.log($`Geolocation + {} not supported by browser.`);
}
});
function showPosition(position) {
var postData = { 'latitude': position.coords.latitude, 'longitude': position.coords.longitude };
$.ajax({
url: 'Base/UpdateLocation',
contentType: 'application/json; charset=utf-8',
type: 'GET',
data: postData,
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (request, data) {
console.log(data);
}
});
};
</script>