locked
Implement an action in controller but not submit or reload page RRS feed

  • Question

  • User1653304669 posted

    Getting Started

    Using jQuery with the ASP.NET MVC framework is very easy. Most of you know that jQuery now ships with ASP.NET MVC. To use jQuery you must include the following script tag (usually in your Master Page or the HTML ‘head’ section:

    <script src="<%= Url.Content("~/Scripts/jquery-1.3.2.js") %>" type="text/javascript"></script>

    This will load the jQuery library from the content folder and make it available on the page.

    Call An Action Method That Returns String Content

    Imagine you have the following action method on a Test controller:

    public string GetDateTimeString()
    
    {
    
        return DateTime.Now.ToString();
    
    }
    

    Note that the above method returns a string. To call this action method using jQuery, you can use the jQuery ‘get’ function as shown below:


    var url = "Test/GetDateTimeString";
    
    $.get(url, null, function(data) {
    
        $("#getDateTimeString").html(data);
    
    });
    


    The jQuery ‘get’ method is a helper method that generates an AJAX GET request. The first parameter is the URL and the third is the callback function when the response is received. The callback function takes one parameter ‘data’ that holds the string content. The following is a screen shot of the resulting data:

    image

    Call An Action Method That Returns A String But Takes Parameters

    This is really the same scenario as the previous case, except the action method expects a parameter. To set the action method parameter we will use the second parameter of the jQuery ‘get’ function. Imagine we have this action method on a Test controller:

    public string ReverseTheString(string input)
    
    {
    
        char[] arr = input.ToCharArray();
    
        Array.Reverse(arr);
    
        return new string(arr);
    
    }
    


    Use the following JavaScript to call this method using AJAX:

    var url = "Test/ReverseTheString";
    
    var stringToReverse = "Bob Cravens";
    
    $.get(url, { input: stringToReverse }, function(data) {
    
        $("#reverseTheString").html(data);
    
    });
    

    Notice that the second parameter to the ‘get’ function now contains a list of key / value pairs. This example supplies one parameter, but can be extended to provide multiple parameters. The result of the above looks like the following:

    image

    Call An Action Method That Returns JSON And Takes Parameters

    The action methods above returned simple strings. Now imagine you want to dynamically fetch more complex data. This is typically formatted in JSON. For example, imagine we want to fetch contact information from the server. More specifically let’s say you have the following ContactInfo class and GetContactInfo action method:


    public class ContactInfo
    
    {
    
        public string FirstName { get; set; }
    
        public string LastName { get; set; }
    
        public string State { get; set; }
    
        public int Age { get; set; }
    
    }
    
    public JsonResult GetContactInfo(int personId)
    
    {
    
        // Use personId to fetch info from repository.
    
        //
    
        // Fake it here.
    
        ContactInfo contactInfo = new ContactInfo
    
                                      {
    
                                          FirstName = "Bob",
    
                                          LastName = "Cravens",
    
                                          State = "Wisconsin",
    
                                          Age = new 43
    
                                      };
    
        return Json(contactInfo);
    
    }
    


    Notice the action method is now returning a ‘JsonResult’. This action method can be called using the following JavaScript:


    var url = "Test/GetContactInfo";
    
    var id = 123;
    
    $.getJSON(url, { personId: id }, function(data) {
    
        $("#name").html(data.FirstName + " " + data.LastName);
    
        $("#state").html(data.State);
    
        $("#age").html(data.Age);
    
    });


    Using Firebug we can sniff the response. A screen shot is shown below:

    imageNotice the response data now has JSON format. The following was rendered in this example:

    image 

    Post Data To An Action Method

    Imagine you have a situation where you want to HTTP POST instead of GET data. For example, suppose you have data that you want to submit via AJAX. Assume for instance you have the following action method:


    [AcceptVerbs(HttpVerbs.Post)]
    
    public string RegisterUser(string firstName, string lastName)
    
    {
    
        // Use the parameters provided to register a new user.
    
        return firstName + " " + lastName + " was successfully registered.";
    
    }


    This action method has attributes that only accept HTTP POST requests. To call this method using AJAX we can use the jQuery ‘post’ function as follows:


    var url = "Test/RegisterUser";
    
    var first = "Bob";
    
    var last = "Cravens";
    
    $.post(url, { firstName: first, lastName: last }, function(data) {
    
        $("#registerUser").html(data);
    
    });


    Notice the ‘post’ function and the ‘get’ function take the same parameters. This is an example of an action method that requires two parameters and returns a string result. This results in the following:

    image

    Post Form Data

    Let’s say you have the following form for submitting new contact information:


    <form id="myForm" action="/Monitor/Test/FormPost" method="post">
    
        <div>First Name: <input name="FirstName" type="text" value="Bob" /></div>
    
        <div>Last Name: <input name="LastName" type="text" value="Cravens" /></div>
    
        <div>Age: <input name="Age" type="text" value="43" /></div>
    
        <input type="submit" value="Save Contact" />
    
        <div id="postResult">?</div>
    
    </form>


    This from calls the ‘FormPost’ action method on the ‘Test’ controller for the ‘Monitor’ application. The following is the action method called when the form is submitted:


    [AcceptVerbs(HttpVerbs.Post)]

    public string FormPost(ContactInfo contactInfo)
    
    {
    
        return contactInfo.FirstName + " " + contactInfo.LastName + " (" + contactInfo.Age + ") has been saved.";
    
    }


    Notice the action method returns a string result. Now assume you want to submit this from using AJAX.  This is easily done using the following JavaScript:


    var f = $("#myForm");
    
    var url = f.attr("action");
    
    var formData = f.serialize();
    
    $.post(url, formData, function(data) {
    
        $("#postResult").html(data);
    
    });


    This JavaScript shows the power of jQuery. With one ‘serialize’ call all the form’s input data is collected and ready to be sent. We can again sniff the post data using Firebug:

    image

    Notice the above action method takes a ‘ContactInfo’ (same as the one introduced earlier) object. No where in this code are we creating this type of object. So who is creating this object? This is the power of the ASP.NET MVC model binder in action. As long as the names (‘FirstName’, ‘LastName’, ‘Age’ in this example) of the input elements match the corresponding property names of the object the model binder will have no problem. The following is a screen shot of the rendered HTML after the form has been submitted:

    image

    Load an MVC Partial View

    The server is often times the best place to generate your HTML content. Adding dynamically generated content based upon the current application state is often necessary. Suppose you have the following action method on your MVC Test controller:


    public ActionResult MyPartialView(string info)
    
    {
    
        ViewData["info"] = info;
    
        return View();
    
    }


    This action method is simplistic. It stored some ‘info’ data into the ViewData dictionary and then returns the following partial view.


    <span>
    
        Your Info: <%= Html.Encode(ViewData["info"]) %>
    
    </span>


    Again, this is a simple partial view that is dynamically generated to display your input info. This partial view can be loaded into the DOM using the jQuery ‘load’ function as follows:


    var url = "Test/MyPartialView";
    
    var info = "This is my information."
    
    $("#partialView").load(url, { info: info });


    Notice the ‘load’ method is a function attached to every jQuery element that is generated with a selector. The above method replaces the HTML of the element with ID of ‘partialView’ with the dynamically generated HTML from the MVC partial view. Using Firebug to sniff the response shows the following:

    image

    Notice the response is HTML. The results look like the following when rendered by the browser.

    image

    Thanks for reading my thread



    Wednesday, May 16, 2012 12:31 PM

All replies

  • User1653304669 posted

    Cool hi every body

    Wednesday, May 16, 2012 10:07 PM