简体   繁体   中英

ASP.Net MVC best practice for handling controller event that returns no view but pops up a window on completion

I am new to asp.net mvc.

I have a page that originally had a link that would use javascript to pop up a window that allowed them to log on to their facebook page.

That worked fine, but now I need to update some data in our database before popping up the window. I added a method (that does not return anything) that is called when the user clicks the link. In the controller method, I update my db and then return nothing (that is, no view is returned.) As soon as the code returns, the original javascript fires and the facebook window is opened.

This approach worked fine for IE, but the javascript does not fire in chrome or firefox. What am I doing wrong?

Here is the original code:

    <a onclick="ShareFacebook('@Model.ShareFacebookTitle', '@Model.ShareFacebookBody');" class="facebook"  target="_blank">
        <img src="/Content/images/socialMediaIcons/facebookIcon.png" alt="Add to Facebook" onmouseover="this.src='/Content/images/socialMediaIcons/colorFacebookIcon.png'"
           onmouseout="this.src='/Content/images/socialMediaIcons/greyFacebookIcon.png'" /></a>

That worked for all 3 browsers.

Then I changed the code to look like this:

    @Ajax.ImageActionLink("/Content/images/socialMediaIcons/facebookIcon.png", "facebook", "/Content/images/socialMediaIcons/colorFacebookIcon.png", "/Content/images/socialMediaIcons/greyFacebookIcon.png",
        "ShareViaFacebook", "ContactUs",
        new { ... paremeters not relevant here },
        new AjaxOptions
        {
            HttpMethod = "POST",
            InsertionMode = InsertionMode.Replace,
            UpdateTargetId = "content-dialog",
            OnComplete = "ShareFacebook('@Model.ShareFacebookTitle', '@Model.ShareFacebookBody');"
        }, null)

And added a controller method:

    public void ShareViaFacebook(... parameters not relevant here)
    {
        //do database update
    }

Basically, I moved the ShareFacebook javascript method from the onclick event in the original code to the OnComplete event in the modified code. As stated, this works fine in IE, but in Chrome and Firefox, the OnComplete event never fires.

Is there a reason this event doesn't fire for Chrome and Firefox and is there something I can do to get it to fire? I tried using the OnSuccess event, but that doesn't fire either. I also tried changing the ShareViaFacebook signature to return an ActionResult and then returning new EmptyResult() in the code. That didn't fix it either. Returning an empty view (View()) or partial view (PartialView()) also did not work.

Ok,

EDIT

I reread your question and while I think the solution below is a good one, the reason you are probably not getting a onSuccess or onComplete firing is because I am not sure they fire without an actual response.

You should setup the .NET action to return something when completed. See the example below on how to do that using a JsonResult.

END EDIT

First and foremost I see what you're attempting to do using MVC razor markup and as much as I love MVC helpers I am going to suggest that you not use them but instead use jQuery ajax calls. MVC Helpers work fine but I feel are more difficult to use than the jQuery version of it.

heres how I would do something like this (I stripped it down to something simpler and hopefully it will not be too confusing

1) create the img tag

<img id='img-id' src='ImageUrl' class='foo' />

2) using jQuery create the bindings

<script type='text/javascript'>
    $('#img-id').click(function(){
        launchFacebookToDotNet();
    });
</script>

3) create the lanchFacebookToDotNet Function

<script type='text/javascript'>
// use jQuery Ajax call and promise pattern to finish calls
var launchFacebookToDotNot = function(){

// make the request
    var request = $.ajax({
        url : '@Url.Action("ActionName","ControllerName"),
        type : 'POST', // or 'GET', get is by default
        data : {
            paramName1 : 'paramValue1',
            paramName2 : 'paramValue2'
        } //etc
    });

    //when done and successful
    request.success(function(){
        ShareFacebook('@Model.ShareFacebookTitle', '@Model.ShareFacebookBody');
    });

    //when error
    request.error(function(){
        alert('there was a server error');
    });
};
</script>

You should also return a JsonResult from the .net controller incase there is a handled error or if you want to customize your response

it will be something like this

 public JsonResult ActionName(){

     // code here to make something awesome happen
     return new JsonResult(new {success = true, message = "I am Json, hear me roar.");
 }

and the response in the ajax call can be handled like this

 // using ajax success example from above

 request.success(function(response){ // the response will be passed in automatically as JSON
     // always do error and value checking but I am skipping it due to time

     if (response.success === true){
          ShareFacebook('@Model.ShareFacebookTitle', '@Model.ShareFacebookBody');
     } else {
          alert(response.message);
     }

    });

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM