rogerthat
rogerthat

Reputation: 1815

update div with Ajax MVC4

I can't seem to understand how to update a div of items after a category is selected. I've got this far and am now confused. How to get the values from the view into the controller to make the query?

 //get <li> clicked and display the items in that category
 $(document).ready(function() {
$('#test li').click(function() {
    var selector = "input[name='" + $(this).id + "value']";
    var catID = $(selector).val(); 

    $.ajax({
        url: "...",
        type: "get",
        data: {//return all the item info},
        success: function(data) {
            //update div contents here?

        }
    });
});
});

Partial to be updated upon which category is clicked

@foreach (var item in Model)
 {

    <ul>

        <li>@item.item_name</li>
        <li><input type="hidden" class="item_id" value="@item.ID" /></li>

    </ul>

 }

Controller

public ActionResult PartialTwo( int id)//how to pass category id?
    {

        var query = from d in db.Items
                    where d.catId==id
                    orderby d.dateAdded
                    select d;
        var results = query;


        return PartialView("_FullInfoPartial", results);
        //returns items in the clicked category  

    }

Upvotes: 0

Views: 1867

Answers (3)

Jatin patil
Jatin patil

Reputation: 4298

Use Ajax.BeginForm as follows,

@using (Ajax.BeginForm("Index", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "youDivId" }))

Using the above and making your controller returning Patial View will update your div with the partial view result.

Upvotes: 0

G&#246;khan Girgin
G&#246;khan Girgin

Reputation: 1164

instead of two li

<li>@item.item_name</li>
<li><input type="hidden" class="item_id" value="@item.ID" /></li>

you can just use one in order to decrease dom size if it is not required

<li data-id="@item.ID">@item.item_name</li>

and you can get the partial view result with $.get easily

$("#test li").on("click",function(){

    var requestPage = "/PartialTwo?id=" + $(this).data("id");
    $.get(requestPage, function(result){
        $("#content").html(result); // where you want to put the result
    });
});

Upvotes: 2

AlexLordThorsen
AlexLordThorsen

Reputation: 8498

I've answered a very similar question over here, though the example was using PHP. The basic idea is the same however. your MVC4 will return some data type that will be turned into HTML (the easiest way is to just return straight HTML) and then you will append this HTML value to a DOM element (in this case, the div item of your choice).

the JQuery would look similar too:

var request = $.ajax({
      type: "POST",
      url: "example.php",
      data: data_obj,
      dataType: "html"
   }).done(function(msg) {
         $("#example_element").append(msg);
      }

Attempting to load a "div" as dynamic content is returned

Upvotes: 1

Related Questions