2

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');
        }
    })
}
3
  • A partial view can be a good practice with using the Ajax options.. And the second I would use join instead of making separate select, Commented Nov 30, 2015 at 1:34
  • What Happen if u write console.log(data) inside the success function? Commented Nov 30, 2015 at 1:37
  • 1
    It unclear what your wanting to do here. First you not passing any parameters to you method so every time you trigger the ajax call you just getting exactly the same data (what is there to update?). And in the success call back your just building an array from the already existing array (a bit pointless). Nowhere are you actually updating the DOM. Commented Nov 30, 2015 at 2:15

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

will this ajax update method give results in foreach loop. i'm working on something similar. my data will have a list in it.
@coder771 Yea, you can loop through it using $.each
if i want to know how 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); structure is created. @shyju
i have a big structure and want to understand how to create it. what can i search for?
@coder771 I suggest you to write a new question with the relevant information, codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.