13.9. ASP.NET MVC and JavaScript

ASP.NET MVC is very much set up for easy integration with popular JavaScript frameworks such as jQuery. For more information on jQuery, please refer to Chapter 12.

You will create a new edit page that utilizes the jQuery libraries to send the contents of a form to the edit controller. To do this, you will format the data as JSON. JSON stands for JavaScript Object Notation and is a very lightweight format to pass around simple classes and properties.

In the film example, a film class formatted as JSON might look something like this:

{ID:"1",Title:"Kung Fu Panda"}

JSON is very easy to construct and has the advantage that JavaScript frameworks understand JSON objects, allowing you to easily access properties with code like this:

alert(Film.Title);

JSON is also a lot less verbose than a typical SOAP request, which might look like this:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <AddFilm xmlns="http://tempuri.org/">
      <objFilm>
        <FilmID>1</FilmID>
        <Title>Kung Fu Panda</Title>
      </objFilm>
    </AddFilm>
  </soap:Body>
</soap:Envelope>

Currently, JSON support in .NET is a bit limited (although expect this to be an area Microsoft develops in the future). The ASP.NET MVC framework, however, has a special action type for working with the JSON requests you will use in the next example.

Let's see how to submit a form using JQuery:

  1. Right-click the Views folder, and add a loosely typed view called EditJSON.

  2. Replace the Content2 placeholder with the following code:

    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    
    <script>
    
        function submit() {
    
            //Get values from form
            var InputFilmID = $("#FilmID").val();
            var InputTitle = $("#Title").val();
            var InputDescription = $("#Description").val();
    
            //Submit client side
            $.ajax({
                type:
            "POST",
                dataType: "json",
                url: "EditJSON",

    data: { FilmID: InputFilmID, Title: InputTitle,
                        Description: InputDescription },
                success: function (result) {
                    alert(result.Message + " updating film " + result.Title);
                    window.location = "../All";
                },
                error: function (error) {
                    alert('error '),
                }
    
            });
        }
    
    
    </script>
    
    
    <form>
    
    ID: <br />
    <%= Html.TextBox("FilmID")%>
    
    <br /> <br />
    
    Title: <br />
    <%= Html.TextBox("Title")%>
    
    <br /> <br />
    
    Description: <br />
    <%= Html.TextBox("Description")%>
    
    
    <br />
    </form>
    
    <input type="button" onclick="javascript:submit();" value="Update" />
    
    </asp:Content>

    NOTE

    The JavaScript code $("#Description").val just means retrieve the value of the element with the ID of Description.

  3. Open the file ~/Controllers/FilmController.cs, and add the following code:

    [AcceptVerbs("GET")]
    public ActionResult EditJSON(int ID)
    {
        return View(filmRepository.GetFilm(ID));
    }

    [AcceptVerbs("POST")]
    public JsonResult EditJSON(BobsMoviesMVC.Models.Film film)
    {
        filmRepository.Update(film);
    
        //Return a very simple JSON response
        return Json(new { Message = "Success", Title = film.Title });
    }

    NOTE

    The return type of this function is of type JsonResult instead of ActionResult because you are passing back a JSON object.

  4. Click F5 to run the application.

  5. Click the Example 5—Edit JSON link. This will open the film with ID 1. (If you have already deleted this film, update the Index view.)

  6. Modify some details, and then click Update.

The film should now have been updated (if it hasn't, ensure that you have referenced the jQuery libraries in your master page, as described in the section "Changing the Layout of MVC Pages"). Note that you passed back the film property in the JSON object returned. That is how easy it is to update the model using client script.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.80.34