streamc
streamc

Reputation: 698

JSON List ASP.net MVC

I have /Views/Movies/Index.cshtml with

<input type="button" id="getmoviex" value="Get moviex" />
<ul id="moviex_list"/>
 <p>
        Title: @Html.TextBox("SearchTitle") <br />
    </p>

I have /Controllers/MoviesController.cs with

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult moviex(string SearchGenre, string SearchTitle, string SearchActor)
    {
        var db = new CinemaContext();
        db.Configuration.ProxyCreationEnabled = false;
        var Movie = from m in db.Movie
                    select m;
        if (!String.IsNullOrEmpty(SearchTitle))
        {
            Movie = Movie.Where(s => s.Title.Contains(SearchTitle));
        }
         return Json(db.Movie.ToList(), JsonRequestBehavior.AllowGet);
    }

I have Javascript.js with

$(document).ready(function () {
    $('#getmoviex').click(function () {
        $.getJSON("/Movies", null, getmoviex);
    });
});

Have I correctly written /Movies? Or this should be /Views/Movies?

function getmoviex(moviex) {
    $("#moviex_list").text("");
    $.each(moviex, function (i) {
        $("#moviex_list").append("<li>" + this + "</li>");
    });
}

How can I display info or list info from my query? Or view some output with error?

Upvotes: 0

Views: 113

Answers (2)

RizkiDPrast
RizkiDPrast

Reputation: 1725

you need to pass your arguments as well in url (GET). Something like this could work:

$('#getmoviex').click(function(event) {
  event.preventDefault();
  $.getJSON("/Movies/moviex?SearchGenre=yuorgenre&SearchTitle=Cal&SearchActor=youractor", function(moviex) {
      var lis;
      //please check the console
      console.log(moviex);
      $.each(moviex, function(b) {
          lis += "<li id='" + b.Id + "'>" + b.Title + "</li>");
      }); document.getElementById("moviex_list").innerHTML += lis;
  });
});

To avoid circular reference in Serializing you may use:

if (String.IsNullOrEmpty(SearchTitle)) {
  return View("Error");
}

var db = new CinemaContext();
var Movie = (from m in db.Movie
            Where m.Title.Contains(SearchTitle)
            select new {
             Id = m.MovieID,
             Title = m.Title // can add more properties
            }).ToList();

return Json(Movie, JsonRequestBehavior.AllowGet);

Upvotes: 1

Andrei
Andrei

Reputation: 56726

First make sure you button click does not trigger a request to server. Preventing default behavior is a standard way of doing it:

$('#getmoviex').click(function (event) {
    $.getJSON("/Movies", null, getmoviex);
    event.preventDefault();
});

As for the URL, it should not be to view, but to action instead. Your action is moviex and controller is Movies, so

$.getJSON("/Movies/moviex", null, getmoviex);

The rest looks fine, so that should do it.

Upvotes: 2

Related Questions