Search code examples
javascriptajaxasp.net-mvcasp.net-web-apihref

How to open open window in new window from javascript using href in asp.net MVC


I have a following code where i am opening an external url link from my asp.net MVC view.

Now I have to add an entry when opening the link. My thinking is that i should do it via some javascript function which will call ajax call to my web api controller and then open a new window of the url

 @{
            var token = Session["SecurityToken"] as AppSecurityToken;
            if (token != null && token.Claims != null)
            {
                foreach (var claim in token.Claims)
                {
                    if (!String.IsNullOrWhiteSpace(claim.Description))
                    {
                        string imagepathv = Url.Content("~/") + "images/" + claim.Name + ".png";
                        string hreftext = $"{claim.Description}?sessionid={token.SessionId}";
                        <li>
                            <a href="" onclick="UserNameAccess('@hreftext');">
                                <img src="@imagepathv" />
                            </a>
                        </li>
                    }
                }
            }
        }


<script lang="javascript" type="text/javascript">
        function UserNameAccess(input) {
            window.open(input, "_blank");


            var baseSiteUrl = '@ConfigurationManager.AppSettings["WebApiBaseUrl"]';
            var request = { "email": "sadasd", "firstname": "asdasd", "lastname": "dasdasda" };

            $.ajax({
                type: "POST",
                url: baseSiteUrl + "DataAccessApi/LogUserClaimAccesshistory",
                data: JSON.stringify(request),
                datatype: "text",
                contentType: "application/json",
                success: function (resultData) {
                    var responseJson = resultData;
                    if (responseJson.Success === true) {
                        alert("success");
                    }
                    else {
                        alert("error1");
                    }
                },
                failure: function (error) {
                    alert(error);
                },
                error: function (jqXhr, textStatus) {

                    if (textStatus === 'timeout') {
                        alert("Request Timeout");
                        //do something. Try again perhaps?
                    } else {
                        alert(jqXhr.statusText);
                    }
                },
                timeout: 30000 // sets timeout to 3 seconds
            });
        }
    </script>       


 public class DataAccessController : ApiController
    {

        [Route("DataAccessApi/LogUserClaimAccesshistory")]
        public MyJsonResponse LogUserClaimAccesshistory(UserClaimHistory request)
        {
            MyJsonResponse result = new MyJsonResponse();
            return result;
        }
    }   


    public class MyJsonResponse
    {
        [JsonProperty]
        public bool Success { get; set; }

        [JsonProperty]
        public string Message { get; set; }

        [JsonProperty]
        public string CustomInfo { get; set; }
    }


    public class UserClaimHistory
    {
        [JsonProperty("email")]
        public string Email { get; set; }

        [JsonProperty("firstname")]
        public string FirstName { get; set; }

        [JsonProperty("lastname")]
        public string LastName { get; set; }
    }

Solution

  • Why don't you use the below code ? Let the a tag do the web page opening, while the JS takes care of the API call.

    Updated answer :

    @{
        var token = Session["SecurityToken"] as AppSecurityToken;
        if(token != null && token.Claims != null)
        {
            foreach(var claim in token.Claims)
            {
                if(!String.IsNullOrWhiteSpace(claim.Description))
                {
                    string imagepathv = Url.Content("~/") + "images/" + claim.Name + ".png";
                    string hreftext = $"{claim.Description}?sessionid={token.SessionId}";
                    <li>
                        <!-- We use the <a> tag to handle the new page opening -->
                        <a href="@hreftext" onclick="UserNameAccess();" target="_blank">
                            <img src="@imagepathv"/>
                        </a>
                    </li>
                }
            }
        }
    }
    
    <!-- The javascript completly ignores the new page, and only focus on the API call -->
    <script lang="javascript" type="text/javascript">
        function UserNameAccess()
        {
            var baseSiteUrl = '@ConfigurationManager.AppSettings["WebApiBaseUrl"]';
            var request = { "email": "sadasd", "firstname": "asdasd", "lastname": "dasdasda" };
    
            $.ajax({
                type: "POST",
                url: baseSiteUrl + "DataAccessApi/LogUserClaimAccesshistory",
                data: JSON.stringify(request),
                datatype: "text",
                contentType: "application/json",
                success: function(resultData)
                {
                    var responseJson = resultData;
                    if (responseJson.Success === true)
                    {
                        alert("success");
                    } else
                    {
                        alert("error1");
                    }
                },
                failure: function(error)
                {
                    alert(error);
                },
                error: function(jqXhr, textStatus)
                {
                    if (textStatus === 'timeout')
                    {
                        alert("Request Timeout");
                        //do something. Try again perhaps?
                    } else
                    {
                        alert(jqXhr.statusText);
                    }
                },
                timeout: 30000 // sets timeout to 3 seconds
            });
        }
    </script>