0

I want to fire a Jquery function from my MVC Action code. Know that it isn't possible via the direct code, If anyone knows how to do this task via any kind of possible forms such as publishing an event or do that with using ajax call or whatever.

Here I have a JQuery Plugin which can be run with the below code.

$('#myModal').Show();

their original calling mechanism was :

<script type="text/javascript">
$(document).ready(function() {
     $('#myButton').click(function(e) {
          e.preventDefault();
      $('#myModal').Show();
     });
});
</script>

A little more explanation:

I don't want most of the code except the line I mentioned. Maybe here we should make it a more simple function before running the provided hack. We don't the button event-handler what we want is : after the Action in the Controller have sent an email call this function $('#myModal').Show();

The Action :

[HttpPost]
public ActionResult Contact(Contact message)
{
    if (ModelState.IsValid)
    {
        string stResult ;
        Emailing.SendEmail(message, out stResult);
        ViewBag.SaveResultMessage = stResult;
    }
    return View(message);
}

Action is called from the Contact View :

    @Html.ValidationSummary(true)
    @using (Html.BeginForm("Contact", "Home", FormMethod.Post, new { name = "send-contact", 
              id = "contactform1"}))
    {           
            if (!String.IsNullOrEmpty(stResult)) 
             {   
                // $('#myModal').Show(); I hoped we could do this way.
             }
        ...
     }

Any sample codes and demo on your provided solution is really appreciated.

Edit (Based on the bAlexandre answer):

your code : $("#btnSubmit").click(function () { // let's show a loading image //$(".myModal").Loading(); // We don't want the load or waiting operations, // Just want to show the final message such as "Successful !" to the user. // I don't think yet it be right but after got sure the Json is returned want to show the message to the user.

        var frm = $("#send-contact"),  // our form
            url = frm.attr("action"),  // our post action
            dta = frm.serialize();     // our data to be posted

        $.post(url, data, function(data) {
            // data has our returned Json from our view

            //$(".myModal").Show(stResult); Instead I want a place like here to just show the result
            $(".error-message").text(data.message); // just to see it, do what you want
            //$(".loading").hide(); // no more loading as we have what we need
        });

-- Also I'm eager to know how to return and show the stResult when the json returned. Thanks for any further completion of you answer and your help.

8
  • How is your action being called? Commented Jul 28, 2013 at 14:29
  • In the Contact page, @using (Html.BeginForm("Contact", "Home", FormMethod.Post, new {... Commented Jul 28, 2013 at 14:31
  • Is it a option to do a jQuery $.post()? Commented Jul 28, 2013 at 14:42
  • I know how to make jquery and it's plugins work but in case of HTTP commands, postbacks and ajax like behavior, I'm novice. Commented Jul 28, 2013 at 14:52
  • Ok I got you, give me a minute Commented Jul 28, 2013 at 14:58

4 Answers 4

4

So, let's assuming you want to tell the user that the email was sent ... or a problem occur.

The idea should be, post the form to the action and wait for the result, showing it to the user.

Let's change your action to

[HttpPost, ValidateAntiForgeryToken]
public ActionResult Contact(Contact message)
{
    string message = "";

    if (ModelState.IsValid)
        Emailing.SendEmail(message, out message);
    else
       message = "Model not valid";

    return Json(new { message = message }); // will return a Json string
}

then in your View side, use:

@using (Html.BeginForm("Contact", "Home", FormMethod.Post, 
          new { name = "send-contact", id = "send-contact"}))
{           
    @Html.AntiForgeryToken() 

    ...

    <input type="button" class="btn-submit" value="Send email" />
}

as well for the script

@section script
{
    <script>
        $(".btn-submit").click(function() {
            // let's show a loading image
            $(".loading").show();

            var frm = $("#send-contact"),  // our form
                url = frm.attr("action"),  // our post action
                dta = frm.serialize();     // our data to be posted

            $.post(url, data, function(data) {
                // data has our returned Json from our view
                $(".error-message").text(data.message); // just to see it, do what you want
                $(".loading").hide(); // no more loading as we have what we need
            });


            return false;
        });
    </script>
}

Some tips about your code:

1 - Avoid using out if you can simply return an object, in your Emailing.SendEmail(message, out stResult); simply write:

stResult = Emailing.SendEmail(message);

make it easier to read and makes it way better understandable.

2 - In your _Layout use a scripts section before the </body> tag and foreach View you can place the scripts right there by invoking @section script { ... }

3 - When posting to your own website, from your own website always use ValidateAntiForgeryToken, it's easier and make it hard, for your example, to someone hack into your form and spam your email...

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

4 Comments

You are right about the idea and after a glanced look I think should be the possible answer. I need a bit of time to test it, thanks for the quality answer and also the hints, a question on a piece of your hints about "out", I found it a good tool in terms of security but do not mean here.
your answer was something a bit new to me which I wanted to go the pass of learning it and it is helping me, Here there are a bit difference between what you provided and what I wanted, I edit the question and will add a section in the bottom based on your answer please take a look at it I will be happy if you can change your answer a bit to address this issue, it's really appreciated, thanks alot
your view needs to return Json, and all you need then is showing what's in data.message. Attach it to any placeholder and show whatever you need... I really don't get your edit as you simply copy/pasted my code, please debug using console.log() or a simple alert so you can see what's going on if you can't understand.
I will clarify my point more, at the moment I have to go, when returned I try to describe the problem in a better format. thanks
0

You can use your "viewBag" result in view to call Jquery function

For eg,

<script type="text/javascript">
@if(ViewBag.SaveResultMessage)
{
    $('#myModal').Show();
}

2 Comments

This is exactly the same as a line in my question which I said I hoped be possible this way, you mean without the <script> tags we can call it directly ?
The if is without @ and code blocks because it's inside a @using.
0

Try ajax call,

            $.ajax({
            type: "POST",
            url: "Contact",
            data: JSON.stringify(message),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function () {
                $('#myModal').Show();
            },
            error: function () {                   

            }
        });

6 Comments

Where to place this ajax code? How to call this from my Action? as I said in terms of ajax I'm a starter.
I want to mark one of these two as the answer, but please reform these based on my questions, thanks for the hints, +1
See you cannot call jquery code from action. but you can call your action from jquery code and on success of the action you can call your precceding code. And you can place ajax call in script.
The Action is completed, (a Post action), now it returns again to the page, I stored the result in the ViewBag. How can I use the two snippets you provided this way dealing with my result.
Can you provide the snipet of your action?
|
0

You can follw steps as follows,

For eg: 1) Create action which will return meassge as string(you can use other Data Types also),

    public string Contact(Contact message)
    { 
        //Demo Code
        string result = "Success"
        return result 
    }

2) Make ajax call and on success callback function of ajax call validate your result and open modal form,

    $.ajax({
            type: "POST",
            url: "Contact",
            data: JSON.stringify(message),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
                if(result.d == "Success")
                    $('#myModal').Show();
            },
            error: function () {                   

        }
    });

2 Comments

Where should I place this Ajax code? So this way you mean instead of returning the "View" or "json" I return a string as a result?
put ajax call in <script>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.