0

我正在尝试将 json 位置值存储在 tempdata 中,我正在使用 json api 获取用户当前位置,并且我想根据位置向用户显示内容,但我无法做到这一点,所以我正在分享我的代码,请大家帮帮我

<script type="text/javascript">

        var strip, strcountry, strcity, strregion, strlatitude, strlongitude, strtimezone

        function GetUserInfo(data) {

            strip = data.host; strcountry = data.countryName; strcity = data.city;

            strregion = data.region; strlatitude = data.latitude; strlongitude = data.longitude;

            strtimezone = data.timezone;

        }

        $(function () {

            BindUserInfo();

        })

        function BindUserInfo() {

            //document.getElementById('lblCity').innerText = strcity;
            $('#term').attr("placeholder", strcity);
            $('#term').attr("value", strcity);



        }

    </script>
    <script type="text/javascript" src="http://smart-ip.net/geoip-json?callback=GetUserInfo"></script>

现在我想从这里获取位置并在 linq 查询中应用,我正在使用 MVC 4 (Razor) 请帮我解决这个问题。

4

1 回答 1

1

根据上面的评论,听起来这一系列事件正在发生:

  1. 用户位于包含此 JavaScript 代码的页面上
  2. 用户单击该页面上的链接以转到另一个页面
  3. 其他页面需要根据此 JavaScript 代码中的值显示数据

如果这是正确的,那么您有许多可用的选项。需要明确的是,所讨论的价值是什么? strcity?:

$('#term').attr("placeholder", strcity);
$('#term').attr("value", strcity);

If so, then when you set that value here you could also potentially set it on perhaps the query string for the link to the next page. Something like this:

$('#someLink').src = '@Url.Action("Index", "Restaurants")?city=' + strcity;

This would use a mix of pre-run server-side code for the root of the link, and client-side code to just append that one value to it. Then the controller method simply accepts city as a parameter:

public ActionResult Index(string city)
{
    // get your list of restaurants and return the view
}

There's no need for TempData in this, you're just sending the value directly to the controller action.

If for whatever reason you don't want to modify the src like that, you could perhaps instead send the value through a form invoked by the link. So instead of an ActionLink to the index action on the restaurants controller, you might have something like this:

@using(Html.BeginForm("Index", "Restaurants", FormMethod.Get))
{
    <a id="restaurantsLink" href="javascript:void(0);">Go to restaurants</a>
    <input type="hidden" name="city" />
}

And JavaScript code later:

$('#restaurantsLink').click(function () {
    $('form').submit();
});

You might need to more uniquely identify that form in the jQuery selector, particularly if there are (or could be) other forms on that page. Then in your original JavaScript code you would just set the value in the hidden input:

$('input[name=city]').val(strcity);

In this second case the controller action would still be the same as the first one, accepting a city string parameter.

于 2013-09-06T20:37:54.250 回答