Mr.Smithyyy
Mr.Smithyyy

Reputation: 1329

Update Model Data in foreach loop with ajax

I need to update this model in my view without a page refresh so I figure ajax is the best option but I'm not sure how to do it.

So I've created an ajax call to give me all my info in an object array but I dont know how to user that in my view.

Models

public class User
{
    public Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

public class Course
{
    public Id { get; set; }
    public string Name { get; set; }
    public string User { get; set; }
}

Controller

public JsonResult userCourseInfo()
{
    if (Session["Username"] != null)
    {
        string user = Session["Username"].ToString();

        var UserInfo = from u in db.Users
                           where u.Username == user
                           select u;

        var UserCourse = from c in db.Courses
                              where c.User == user
                              select c;

        var model = new UserCourseModel { user = UserInfo, course = UserCourse };

        return Json(model, JsonRequestBehavior.AllowGet);
    }
    else
    {
        return null;
    }
}

View

<ul>
    @foreach (var item in Model.course)
    {
        <li>
            <div class="row">
                <div class="col-md-5">
                    <div class="map-panel-box-general">
                        <p>@Html.DisplayFor(modelItem => item.Id)</p>
                        <p>@Html.DisplayFor(modelItem => item.Name)</p>
                        <p>@Html.DisplayFor(modelItem => item.User)</p>
                    </div>
                </div>
            </div>
        </li>
    }
</ul>

Javascript

function updatePanel()
{
    $.ajax(
    {
        url: "@Url.Action("userCourseInfo", "Users")",
        type: "GET",
        dataType: "json",
        success: function(data)
        {
            panelInfo = [];

            $.each (data.course, function(index, courses)
            {
                panelInfo.push({ courseId: course.Id, courseName: course.Name, courseUsers: course.User })
            })

        },
        error: function()
        {
            console.log('failed');
        }
    })
}

Upvotes: 2

Views: 5847

Answers (1)

Shyju
Shyju

Reputation: 218702

I am not quite sure what you are trying to do. But if you want to update your markup inside the foreach loop with the response coming from the ajax call, You can simply read the json properies and build HTML and replace the existing html with that.

First of all you need to give an id to your UL element so that we can select it using jQuery later

<ul id="myCourses">

</ul>

Your action method is returning the Json representation of the an object of UserCourseModel class which has 2 properties , user and course, both are collection types(Arrays). I am not sure you really want the user property as you are planning to replace only the list of courses (your foreach loop)

Let's say the response from your ajax call looks like the below JSON

{
    "user": [{
        "Id": 23,
        "Username": "Scott",
        "Password": null
    }],

    "course": [{
        "Id": 2,
        "Name": "CS",
        "User": {
            "Id": 23,
            "Username": "Scott",
            "Password": null
        }
    }]
}

you can acccess it like this

success: function(data)
{
  if(data!=null)
  {       
    var newHtml = "";
    $.each(data.course, function (index, course) {
      newHtml += '<li><div class="row"><div class="col-md-5">
                                     <div class="map-panel-box-general">';
      newHtml += '<p>' + course.Id + '</p>';
      newHtml += '<p>' + course.Name + '</p>';
      if (course.User != null) {
        newHtml += '<p>User Id ' + course.User.Id + '</p>';
        newHtml += '<p>User name ' + course.User.Username + '</p>';
      }
      newHtml += '</li>';       
    });
   $("#myCourses").html(newHtml);
  }

}

I have been doing this approach to update UI dynamically from ajax method calls until i ran into Javascript MVC frameworks like Angualar JS/ Knockout js which can update the UI from model data .You should look into those.

Upvotes: 3

Related Questions