TextBoxFor does not display upcted data but DisplayFor does

Arryamsetty, Rahul (Contractor) 1 Reputation point
2022-03-17T13:52:06.777+00:00

184156-error-display-data.pngHI,

I have a MVC webpage displaying Users data in grid format and also can be edited directly (text boxes) at the first half of the screen and 2nd half of the screen display text boxes to add new users data.

I have search data option in the top of the web page. Everything works fine when filtering the Data. Only issue is the filtered Data is not refreshed in the UI when using @azzedinehtmlsql .TextBoxFor but it displays the correct Data when using
@azzedinehtmlsql .DisplayFor as shown in the image. I am so confused.

@for (int i = 0; i < Model.UserList.Count(); i++)  
         {  
     <tr>  
         <td>  
             @Html.CheckBoxFor(x => x.UserList[i].IsSelected)  
         </td>  
         <td>  
             @Html.TextBoxFor(x => x.UserList[i].Id)  
         </td>  
         <td>  
             @Html.DisplayFor(x => x.UserList[i].Name)  
             @Html.ValidationMessageFor(x => x.UserList[i].Name, "", new { @class = "text-danger" })  
         </td>  
         <td>  
             @Html.TextBoxFor(x => x.UserList[i].Name)  
             @*@Html.ValidationMessageFor(x => x.UserList[i].Name, "", new { @class = "text-danger" })*@  
         </td>  
         <td>  
             @Html.TextBoxFor(x => x.UserList[i].Age)  
             @Html.ValidationMessageFor(x => x.UserList[i].Age, "", new { @class = "text-danger" })  
         </td>  
         ................  
     </tr>      
         }   

Controller COde:      
 [HttpPost]  
         public ActionResult Search(UserViewModel vm, string currentSortOrder, int? page)  
         {  
             int pageSize = 10;  int pageIndex = 1;    pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;      
             StoreSearchParameters(vm);  
             List<Models.UserModel> tmpLst = vm.PopulateData();      
            .....  
            .....  
             if (string.IsNullOrEmpty(vm.SearchName) == false)  
             {  
                 tmpLst = tmpLst.Where(x => x.Name.Contains(vm.SearchName)).ToList();  
             }  
             if (string.IsNullOrEmpty(vm.SearchId) == false)  
             {  
                 UserModel filteredData = tmpLst.Find(x => x.Id == Convert.ToInt32(vm.SearchId));  
                 if (filteredData != null)  
                 {  
                     tmpLst = new List<UserModel>();  
                     tmpLst.Add(filteredData);  
                 }  
                 else  
                 {  
                     tmpLst.Clear();  
                 }  
             }      
             vm.PagedUsersList = tmpLst.ToPagedList(pageIndex, pageSize);  
             vm.UserList =vm.PagedUsersList.ToList();      
             return View("Index", vm);  
         }  

View Model:   
  
  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using View_List_Edit_Sort_Filter.Models;  
  
namespace View_List_Edit_Sort_Filter.ViewModel  
{  
    public class UserViewModel  
    {  
        public List<UserModel> UserList { get; set; }  
  
        public PagedList.IPagedList<UserModel> PagedUsersList { get; set; }  
  
        public List<NewUserModel> NewUserList { get; set; }  
  
        public string SearchId { get; set; }  
  
        public string SearchName { get; set; }  
  
        public string SearchAge { get; set; }  
  
        public string SearchInformation { get; set; }  
  
        public UserViewModel()  
        {  
            Initialize();  
            PopulateData();  
        }  
  
        internal List<UserModel> PopulateData()  
        {  
            List<UserModel> userList = new List<UserModel>();  
            //Mocking Data as if it comes from the DataBase.  
            for (int i = 0; i < 46; i++)  
            {  
                userList.Add(new UserModel() { Id = i, Name = string.Concat("User", i.ToString()), Age = 20 + i, Information = string.Concat("User", i.ToString(), "Info"), CreatedDate = DateTime.Now, CreatedBy = Environment.UserName, UpdatedBy = Environment.UserName, UpdatedDateTime = DateTime.Now });  
            }  
  
            return userList;  
        }  
  
        private void Initialize()  
        {  
            UserList = new List<UserModel>();  
  
            NewUserList = new List<NewUserModel>();  
            for (int i = 0; i < 6; i++)  
            {  
                NewUserList.Add(new NewUserModel());  
            }  
        }  
    }  
}  

184215-debug-quickwatch-listdata.png

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,323 questions
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 26,246 Reputation points
    2022-03-17T17:44:09.44+00:00

    The following is a basic example of a service. Internally the service uses an UserEntity and returns a UserViewModel.

     public interface IUserService
        {
            UserViewModel GetUserById(int id);
            List<UserViewModel> GetUsers();
        }
    
        public class UserService : IUserService
        {
            private readonly List<UserEntity> MockUsers = new List<UserEntity>();
            public UserService()
            {
                PopulateData();
            }
    
            internal void PopulateData()
            {
    
                for (int i = 0; i < 46; i++)
                {
                    MockUsers.Add(new UserEntity()
                    {
                        Id = i,
                        Name = string.Concat("User", i.ToString()),
                        Age = 20 + i,
                        Information = string.Concat("User", i.ToString(), "Info"),
                        CreatedDate = DateTime.Now,
                        CreatedBy = Environment.UserName,
                        UpdatedBy = Environment.UserName,
                        UpdatedDateTime = DateTime.Now
                    });
                }
    
            }
    
            public List<UserViewModel> GetUsers()
            {
                return MockUsers.Select( u => new UserViewModel()
                {
                    Id = u.Id,
                    Name = u.Name,
                    Age = u.Age,
                    Information = u.Information,
                    CreatedDate = DateTime.Now,
                    CreatedBy = Environment.UserName,
                    UpdatedBy = Environment.UserName
                }).ToList();
            }
    
            public UserViewModel? GetUserById(int id)
            {
                return MockUsers.Select(u => new UserViewModel()
                {
                    Id = u.Id,
                    Name = u.Name,
                    Age = u.Age,
                    Information = u.Information,
                    CreatedDate = DateTime.Now,
                    CreatedBy = Environment.UserName,
                    UpdatedBy = Environment.UserName
                }).FirstOrDefault(u => u.Id == id);
    
            }
        }
    

  2. AgaveJoe 26,246 Reputation points
    2022-03-17T18:46:22.073+00:00

    In my project I am planning not to use the API or Service.

    That's a bad idea. You'll want to use a service pattern or you'll end up with duplicate code.

    Later I am planning to replace the mocking with the Entity Framework DB calls.

    Your current design will not translate well to Entity Framework. You're better off starting with Entity Framework then refactoring rather than your current approach. Better yet, go through the tutorial I linked in my previous post. I guarantee you'll learn a lot of valuable MVC coding patterns.

    For example, rather than creating several List<T> you can apply many filters to a single IQuerable<T> or IEnumerable<T>.

        public class UserFilterViewModel
        {
            public int? Id { get; set; }
            public string Name { get; set; }
            public int? Age { get; set; }
            public string Information { get; set; }
        }
    

    Added to the service.

    public List<UserViewModel> FilterUsers(UserFilterViewModel filter)
    {
        var query = MockUsers.Select(u => new UserViewModel()
        {
            Id = u.Id,
            Name = u.Name,
            Age = u.Age,
            Information = u.Information,
            CreatedDate = DateTime.Now,
            CreatedBy = Environment.UserName,
            UpdatedBy = Environment.UserName
        });
    
        if(!String.IsNullOrEmpty(filter.Name))
        {
            query.Where(m => m.Name == filter.Name);
        }
        if (filter.Age.HasValue)
        {
            query.Where(m => m.Age == filter.Age.Value);
        }
        if (!String.IsNullOrEmpty(filter.Information))
        {
            query.Where(m => m.Information == filter.Information);
        }
        if (filter.Id.HasValue)
        {
            query.Where(m => m.Id == filter.Id);
        }
    
        return query.ToList();
    } 
    

    I think the problem you are currently experiencing will go away if you fix the design.