1

I have made a JavaScript function IPDetection() and I want to call this function from an MVC action result. How can I do this?

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    function IPDetction() {
        $.getJSON("http://ip-api.com/json/?callback=?", function (data) {
            var items = [];
            $.each(data, function (key, val) {
                if (key == 'city') {
                    alert("DetectedCityName=" + val);
                }
                if (key == 'region') {
                    alert("DetectedRegionName=" + val);
                }
            });
        });
    }
</script>
0

1 Answer 1

1

I think you can use @ViewBag for this purpose like:-

Controller:

public ActionResult YourActionName()
{
    ViewBag.CallJSFuncOnPageLoad = "IPDetction();";
    return View();
}

View

<script type="text/javascript">
   @Html.Raw(ViewBag.CallJSFuncOnPageLoad)
</script>

Hope it helps!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this ... this is code is correct and working fine ......but one problem is occurred ..Please also see this .. I have fetch the DetectedCityName and DetectedRegionName in Contoller from this script so please give me the solution for this......Thanks again...........
@SRAspNet you can make an ajax call and send those as param to be processed on server side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.