locked
How to update model from HomeController RRS feed

  • Question

  • User1451609391 posted

    Hello. I have a site with a search textbox. There is an onclick event hooked up to a javascript function. In that javascript function i make an ajax call to my HomeController. I am doing this from my home view. The ajax call does work. It looks like the following code.

            
    
            var groupMember = new Object();
            groupMember.group = group;
            groupMember.groupMemberName = memberName;
    
            if (employee !== null) {
                $.ajax({
                    type: "POST",
                    url: "/Home/SearchGroupMembers",
                    data: JSON.stringify(groupMember),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        if (response !== null) {
    
    
                            alert("running");
    
    
    
                        } else {
                            //  alert("Something went wrong");
                        }
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            }
    
    
    

    In the controller I have a function that looks like this.

           [HttpPost]
            public ActionResult SearchGroupMembers(string groupMemberName,string group) {
    
        
                List<User> searchedUsers1 = new List<User>();
    
                User newUser = new User();
                User newUser1 = new User();
                User newUser2 = new User();
                User newUser3 = new User();
    
    
                searchedUsers1.Add(newUser);
                searchedUsers1.Add(newUser1);
                searchedUsers1.Add(newUser2);
                searchedUsers1.Add(newUser3);
    
                hvm.searchedUsers = searchedUsers1;
    
    
                return View(hvm);
    
    };

    I want to click the search button , then retentive the search results from the homecontroller and update the model in the home controller. My search results are a list of users. This list is suppost to load a table and populate its rows like the following.

                <table style="Position: absolute; top: 0px; width: 100%; height: 100%;">
                    <thead style="height:30px;">
                    <th Width="10%" style="text-align:left;">Title</th>
                    <th Width="10%" style="text-align:left;">Id</th>
                    <th Width="10%" style="text-align:left;">Catagory</th>
                    <th Width="10%" style="text-align:left;">Topic</th>
                    <th Width="10%" style="text-align:left;">Text</th>
                    <th Width="10%" style="text-align:left;">dateTime</th>
                    <th Width="10%" style="text-align:left;">View</th>
                    <th Width="10%" style="text-align: left;">Delete</th>
                    </thead>
                    @{
                        int iii = 0;
                        string background1 = "white";
                    }
    
                    @foreach (User member in Model.searchedUsers)
                    {
                        string id = member.Id.ToString();
    
                        if (iii == 0) { background1 = "white"; } else { background1 = "gray"; }
                        <tr Width="100%" style="text-align :left; height:30px; background:@(background1);" onclick="highlightPendingListItem(this) ">
                            <td Width="10%" style="text-align :left;">@(member.Title + " title")</td>
                            <td Width="10%" style="text-align :left;">@(member.Id + " id")</td>
                            <td Width="10%" style="text-align: left;">@(member.Catagory + " cat")</td>
                            <td Width="10%" style="text-align :left;">@(member.Topic + " topic")</td>
                            <td Width="10%" style="text-align: left;">@(member.Text + " text")</td>
                            <td Width="10%" style="text-align: left;">@(member.dateTime + " dt")</td>
                            <td Width="10%" style="text-align: left;"><input type="button" value="View" onclick="location.href='@Url.Action("Index", "Home", new { pendingId = "4545", catagory = "general" })'" class="myButton" /></td>
                            <td Width="10%" style="text-align :left;"><img src="../Content/Images/close-delete-exit-icone-8590-32.png" onclick="location.href='@Url.Action("Index", "Home", new { pendingId = "4545", catagory = "general" })'" style="cursor:pointer;" /></td>
                        </tr>
                        iii++; if (iii == 2) { iii = 0; }
                    }
    
                </table>

    I am new to mvc5 but have lots of experience with wpf. In wpf you just update the model and where ever the list is bound to in the view the list will change. I think i am missing something maybe some settings or something is needed. Hope someone understands what i am trying to do thanks for the help.

    Wednesday, July 1, 2020 6:13 PM

Answers

  • User1686398519 posted

    Hi johnboyman12,

    According to your needs, I suggest you use ajax, and fill the table through jquery. Please refer to this example for details.

    • For testing, I created a model and simulated some data.
    • Based on the code you give, I suggest you use "table-striped" in bootstrap, which can help you achieve the table style you need.
    • The label of your form needs to be modified. There must be a <tr> tag inside the <thead> tag.

    Model

        public class showModel
        {
            public List<User> searchedUsers { get; set; }
        }
        public class User
        {
            [Key]
            public int Id { get; set; }
            public string Comment { get; set; }
            public string Title { get; set; }
            public string Catagory { get; set; }
            public string Topic { get; set; }
            public string Text { get; set; }
            public string dateTime { get; set; }
        }

    Controller

            public ActionResult test()
            {
                showModel hvm = new showModel();
                List<User> Rawdata = new List<User>();
                for (int i = 6; i <11; i++)
                {
                    User newUser = new User {
                        Id = i,
                        UserName = "Test" + i,
                        Title = "Title" + i,
                        Catagory = "Catagory" + i,
                        Topic = "Topic" + i,
                        Text = "Text" + i,
                        dateTime="2020-06-30"
                    };
                    Rawdata.Add(newUser);
                }
                hvm.searchedUsers = Rawdata;
                return View(hvm);
            }
            [HttpPost]
            public ActionResult SearchGroupMembers(string groupMemberName, string group)
            {
                //Assuming that the query is made here, the result is hvm
                showModel hvm = new showModel();
                List<User> searchedUsers1 = new List<User>();
                for(int i = 0; i < 5; i++)
                {
                    User newUser = new User
                    {
                        Id = i,
                        UserName = "Test" + i,
                        Title = "Title" + i,
                        Catagory = "Catagory" + i,
                        Topic = "Topic" + i,
                        Text = "Text" + i,
                        dateTime ="2020-06-30"
                    }; 
                    searchedUsers1.Add(newUser);
                }
                hvm.searchedUsers = searchedUsers1;
                return Json(hvm,JsonRequestBehavior.AllowGet);
            }

    Page

    @model WebApplication5.Models.showModel
    <p>here is the top</p>
    @for (int i = 0; i < 30; i++)
    {
        @i<br />
    }
    @Html.DisplayName("group")
    @Html.TextBox("group", "", new { id = "group" })
    @Html.DisplayName("memberName")
    @Html.TextBox("memberName", "", new { id = "memberName" })
    <button id="submitbtn">submit</button>
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Title</th>
                <th>Id</th>
                <th>Catagory</th>
                <th>Topic</th>
                <th>Text</th>
                <th>dateTime</th>
                <th>View</th>
                <th>Delete</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var member in Model.searchedUsers)
            {
                string id = @member.Id.ToString();
                <tr onclick="highlightPendingListItem(this) ">
                    <td>@(member.Title)</td>
                    <td>@(member.Id)</td>
                    <td>@(member.Catagory)</td>
                    <td>@(member.Topic)</td>
                    <td>@(member.Text)</td>
                    <td>@(member.dateTime)</td>
                    <td><input type="button" value="View" onclick="location.href='@Url.Action("Index", "Home", new { pendingId = "4545", catagory = "general" })'" class="myButton" /></td>
                    <td><img src="../Content/Images/close-delete-exit-icone-8590-32.png" onclick="location.href='@Url.Action("Index", "Home", new { pendingId = "4545", catagory = "general" })'" style="cursor:pointer;" /></td>
                </tr>
            }
        </tbody>
    </table>
    @section scripts{
        <script>
            //if (employee !== null) {
            $("#submitbtn").click(function () {
                var group = $("#group").val();
                var memberName = $("#memberName").val();
                var groupMember = new Object();
                groupMember.group = group;
                groupMember.groupMemberName = memberName;
                $.ajax({
                    type: "POST",
                    url: "@Url.Action("SearchGroupMembers")",
                    data: JSON.stringify(groupMember),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        if (data !== null) {
                            $("table tbody").empty();
                            alert("run");
                            // console.log(response.responseText)
                            var item2 = "";
                            $.each(data.searchedUsers, function (n, value) {
                                // alert(n + ' ' + value.Title);
                                var item = "";
                                item += "<tr onclick='highlightPendingListItem(this)'>" +
                                    "<td>" + value.Title+"</td>" +
                                    "<td>" + value.Id+"</td>" +
                                    "<td>" + value.Catagory+"</td>" +
                                    "<td>" + value.Topic+"</td>" +
                                    "<td>" + value.Text+"</td>" +
                                    "<td>" + value.dateTimes+"</td>" +
                                    " <td><input type='button' value='View' onclick='location.href='' class='myButton' /></td>" +
                                    "<td><img src='../Content/Images/close-delete-exit-icone-8590-32.png' onclick='location.href='' style='cursor:pointer;' /></td>";
                                item2 += item;
                            });
                            $("table").append(item2);
                        } else {
                            alert("Something went wrong");
                        }
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
            //}
        </script>
    }

    Here is the result.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 2, 2020 10:53 AM

All replies

  • User475983607 posted

    The server response returns to the AJAX function.  It is up to you to write code that reads the response and updates the current page; the DOM.  As written it would be easier to replace the AJAX function with a standard HTML form post or get.

    Is there a reason why you want to use AJAX?

    Wednesday, July 1, 2020 9:28 PM
  • User1451609391 posted

    I used ajax because the only way i can stop the page from returning to the top on refresh is with java script code. Also i update the scroll location. 

    event.stopPropagation(); event.preventDefault();

    Once I got it working the way i want it I kept on using ajax after that.

    So after I run the function that is in my home controller. Will the page reload and will the table update its list?

    Should i use this instead of ajax? If I do will the table list in the view update when the page refreshes.

      @using (Html.BeginForm("SearchForUsers", "Home", FormMethod.Post))
    {

    Wednesday, July 1, 2020 10:46 PM
  • User1686398519 posted

    Hi johnboyman12,

    According to your needs, I suggest you use ajax, and fill the table through jquery. Please refer to this example for details.

    • For testing, I created a model and simulated some data.
    • Based on the code you give, I suggest you use "table-striped" in bootstrap, which can help you achieve the table style you need.
    • The label of your form needs to be modified. There must be a <tr> tag inside the <thead> tag.

    Model

        public class showModel
        {
            public List<User> searchedUsers { get; set; }
        }
        public class User
        {
            [Key]
            public int Id { get; set; }
            public string Comment { get; set; }
            public string Title { get; set; }
            public string Catagory { get; set; }
            public string Topic { get; set; }
            public string Text { get; set; }
            public string dateTime { get; set; }
        }

    Controller

            public ActionResult test()
            {
                showModel hvm = new showModel();
                List<User> Rawdata = new List<User>();
                for (int i = 6; i <11; i++)
                {
                    User newUser = new User {
                        Id = i,
                        UserName = "Test" + i,
                        Title = "Title" + i,
                        Catagory = "Catagory" + i,
                        Topic = "Topic" + i,
                        Text = "Text" + i,
                        dateTime="2020-06-30"
                    };
                    Rawdata.Add(newUser);
                }
                hvm.searchedUsers = Rawdata;
                return View(hvm);
            }
            [HttpPost]
            public ActionResult SearchGroupMembers(string groupMemberName, string group)
            {
                //Assuming that the query is made here, the result is hvm
                showModel hvm = new showModel();
                List<User> searchedUsers1 = new List<User>();
                for(int i = 0; i < 5; i++)
                {
                    User newUser = new User
                    {
                        Id = i,
                        UserName = "Test" + i,
                        Title = "Title" + i,
                        Catagory = "Catagory" + i,
                        Topic = "Topic" + i,
                        Text = "Text" + i,
                        dateTime ="2020-06-30"
                    }; 
                    searchedUsers1.Add(newUser);
                }
                hvm.searchedUsers = searchedUsers1;
                return Json(hvm,JsonRequestBehavior.AllowGet);
            }

    Page

    @model WebApplication5.Models.showModel
    <p>here is the top</p>
    @for (int i = 0; i < 30; i++)
    {
        @i<br />
    }
    @Html.DisplayName("group")
    @Html.TextBox("group", "", new { id = "group" })
    @Html.DisplayName("memberName")
    @Html.TextBox("memberName", "", new { id = "memberName" })
    <button id="submitbtn">submit</button>
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Title</th>
                <th>Id</th>
                <th>Catagory</th>
                <th>Topic</th>
                <th>Text</th>
                <th>dateTime</th>
                <th>View</th>
                <th>Delete</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var member in Model.searchedUsers)
            {
                string id = @member.Id.ToString();
                <tr onclick="highlightPendingListItem(this) ">
                    <td>@(member.Title)</td>
                    <td>@(member.Id)</td>
                    <td>@(member.Catagory)</td>
                    <td>@(member.Topic)</td>
                    <td>@(member.Text)</td>
                    <td>@(member.dateTime)</td>
                    <td><input type="button" value="View" onclick="location.href='@Url.Action("Index", "Home", new { pendingId = "4545", catagory = "general" })'" class="myButton" /></td>
                    <td><img src="../Content/Images/close-delete-exit-icone-8590-32.png" onclick="location.href='@Url.Action("Index", "Home", new { pendingId = "4545", catagory = "general" })'" style="cursor:pointer;" /></td>
                </tr>
            }
        </tbody>
    </table>
    @section scripts{
        <script>
            //if (employee !== null) {
            $("#submitbtn").click(function () {
                var group = $("#group").val();
                var memberName = $("#memberName").val();
                var groupMember = new Object();
                groupMember.group = group;
                groupMember.groupMemberName = memberName;
                $.ajax({
                    type: "POST",
                    url: "@Url.Action("SearchGroupMembers")",
                    data: JSON.stringify(groupMember),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        if (data !== null) {
                            $("table tbody").empty();
                            alert("run");
                            // console.log(response.responseText)
                            var item2 = "";
                            $.each(data.searchedUsers, function (n, value) {
                                // alert(n + ' ' + value.Title);
                                var item = "";
                                item += "<tr onclick='highlightPendingListItem(this)'>" +
                                    "<td>" + value.Title+"</td>" +
                                    "<td>" + value.Id+"</td>" +
                                    "<td>" + value.Catagory+"</td>" +
                                    "<td>" + value.Topic+"</td>" +
                                    "<td>" + value.Text+"</td>" +
                                    "<td>" + value.dateTimes+"</td>" +
                                    " <td><input type='button' value='View' onclick='location.href='' class='myButton' /></td>" +
                                    "<td><img src='../Content/Images/close-delete-exit-icone-8590-32.png' onclick='location.href='' style='cursor:pointer;' /></td>";
                                item2 += item;
                            });
                            $("table").append(item2);
                        } else {
                            alert("Something went wrong");
                        }
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
            //}
        </script>
    }

    Here is the result.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 2, 2020 10:53 AM
  • User1451609391 posted

    Amazing very big help. Thanks a lot answered everything and more.

    Thursday, July 2, 2020 3:47 PM