locked
How to add user input items to collection and send it Post to action method RRS feed

  • Question

  • User1094269964 posted

    I have form  and within the form the user will enter data in textbox and click on add. The user entered data will be added to a table.

    Like that user will add many rows to that table. Final submit button will cause form post and it has to take all the rows as object collection and give it to action method 

    Below is the code . Please help me how to do this . 

    Here User will enter user details and click on add button which will added to the table below.

     public class UserModel
        {
            public List<User> users { get; set; }
    
            public UserModel()
            {
                this.users = new List<User>()
                {
                    new User(){UserId=1,UserName="user1",UserRole="Admin",IsActive=true,IsNewUser=false},
                    new User(){UserId=2,UserName="user2",UserRole="Customer",IsActive=true,IsNewUser=false},
                    new User(){UserId=3,UserName="user3",UserRole="Employee",IsActive=true,IsNewUser=false},
                    new User(){UserId=4,UserName="user4",UserRole="Employee",IsActive=false,IsNewUser=false},
                };
    
            }
        }
    
        public class User
        {
            public int UserId { get; set; }
            public string UserName { get; set; }
            public string UserRole { get; set; }
            public bool IsActive { get; set; }
            public bool IsNewUser { get; set; }
        }
     public class UserController : Controller
        {
            // GET: UserController
            public ActionResult Index()
            {
                UserModel userModel = new UserModel();
                return View(userModel);
            }
    
            [HttpPost]
            public ActionResult Index(UserModel model)
            {
                
                //model.users = Here i want to get all the records which are the table
                return View();
            }
    
           
        }
     public class AppSession
        {
            public List<string> Roles { get; set; }
            
           
            public AppSession()
            {
                this.Roles = new List<string>()
                {
                    "Admin","Customer","Employee"
                };
            }
    
            public static void SaveInSession(HttpSessionState state,AppSession session)
            {
                state["session"] = session;
            }
    
            public static AppSession LoadSession(HttpSessionState state)
            {
                if(state["_session"] ==null)
                {
                    return new AppSession();
                }
                return state["_session"] as AppSession;
            }
        }
    @*Partial View  =>UserAdd.cshtml*@ 
    
    @model SampleApplication.Models.User
    
    @{ 
        var appSession = SampleApplication.AppSession.LoadSession(HttpContext.Current.Session);
        var userRoles = appSession.Roles.Select(item => new SelectListItem { Value = item, Text = item });
    }
    <table>
        <tr><td>@Html.Label("UserId", "UserId")</td>
            <td>@Html.TextBoxFor(user => user.UserId)</td>
        </tr>
    
        <tr><td>@Html.Label("UserName", "UserName")</td>
            <td>@Html.TextBoxFor(user => user.UserName)</td>
        </tr>
    
        <tr><td>@Html.Label("Role", "Role")</td>
            <td>@Html.DropDownListFor(user => user.UserRole, userRoles, "SELECT")</td>
        </tr>
    
        <tr><td>@Html.Label("IsActive", "IsActive")</td>
            <td><div id="divActive">
                @Html.RadioButtonFor(user => user.IsActive, "false", new { id = "InActive" })
                    @Html.Label("InActive", "InActive")
    
                    @Html.RadioButtonFor(user => user.IsActive, "true", new { id = "Active" })
                    @Html.Label("Active", "Active")
                </div>
            </td>
        </tr>
    
    
        
        <tr>
            <td>
                <input type="submit" name="btnSumit" id="btnAddToGrid" value="AddToGrid" />
            </td>
    
        </tr>
    </table>
    @model SampleApplication.Models.UserModel
    @using SampleApplication.Models
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    
    @{
        var appSession = SampleApplication.AppSession.LoadSession(HttpContext.Current.Session);
    
        var user = new SampleApplication.Models.User();
    
    }
    
    @using (Html.BeginForm("Test", "User", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        @Html.Partial("UserAdd", user)
    
        <hr />
        <table border="1" cellpadding="10" id="tblUser">
            <tr>
                <th>UserId</th>
                <th>UserName</th>
                <th>UserRole</th>
                <th>IsActive</th>
                <th>IsNewUser</th>
                <th colspan="2">Actions</th>
            </tr>
            @foreach (var item in Model.users)
            {
                <tr>
                    <td>@item.UserId</td>
                    <td>@item.UserName</td>
                    <td>@item.UserRole</td>
                    <td>@item.IsActive</td>
                    <td>@item.IsNewUser</td>
                    <td><button class='delete'>Del</button></td>
                </tr>
            }
        </table>
    
        <br /> <br />
        <input type="submit" name="btnSumit" value="SaveToDatabase" />
    
        <br />
    
        
    }
    
    @section Scripts {
        <script>
    
            $("#btnAddToGrid").click(function (e) {
                e.preventDefault()
                var UserId = $("#UserId").val();
                var UserName = $("#UserName").val();
                var UserRole = $("#UserRole option:selected").text();
    
                var selected = $("#divActive input[type='radio']:checked");
                if (selected.length > 0) {
                    selectedVal = selected.val();
                }
                var IsActive = selectedVal
                var IsNewUser = true;
                var newRow = "<tr><td>" + UserId + "</td><td>" + UserName + "</td><td>" + UserRole + "</td><td>" + IsActive + "</td><td>" + IsNewUser + "</td><td><button class='delete'>Del</button></td> </tr>";
                $("#tblUser tbody").append(newRow);
            });
    
            $(".delete").click(function (e) {          
               $(this).closest("tr").remove();       
    
          
        </script>
    }
    
    

    Friday, July 24, 2020 8:21 PM

All replies

  • User-474980206 posted

    Only form fields are included in a submit. So when you add the grid row, you need to include a hidden field for each value. With this approach only the added field will be posted. 

    Saturday, July 25, 2020 1:40 AM
  • User1094269964 posted

    Thanks for your response.

    Could you please help me  with some sample  code with the above example

    Saturday, July 25, 2020 12:28 PM
  • User1686398519 posted

    Hi bsurendiran,

    You need to pay attention to some points, I modified your code.

    1. You need to put the script that adds many rows to the table (click event of the button whose Id is called btnAddToGrid on the Index page) on the partial view page,otherwise it will not work. 
    2. bsurendiran

      <input type="submit" name="btnSumit" id="btnAddToGrid" value="AddToGrid" />

      bsurendiran

      <td><button class='delete'>Del</button></td>

      bsurendiran

      <td><button class='delete'>Del</button></td>

      • The type of the "delete" and "AddToGrid" buttons should be designated as "button", otherwise the form submission will be triggered.
    3. bsurendiran

       $(".delete").click(function (e) {          
                 $(this).closest("tr").remove();  
      • "}}" is missing after this function.
    4. Because the controller gets the value through the name attribute of the tag. Since the data you added through js did not add the name property to it, you cannot get the value of them.
      • One way is to add a name. For more detailed writing, please refer to: https://forums.asp.net/t/2167383.aspx.
      • Another method is to get the table data and send it to the controller through json, specifically refer to the modified code below.

    Partial view

    <td><input type="button" name="btnSumit" id="btnAddToGrid" value="AddToGrid" /></td>
    <script>
    $("#btnAddToGrid").click(function (e) {
    ... ...//These codes have not been modified, so I omitted them.
    var newRow = "<tr><td>" + UserId + "</td><td>" + UserName + "</td><td>" + UserRole
    + "</td><td>" + IsActive + "</td><td>" + IsNewUser
    + "</td><td><button type='button' class='delete'>Del</button></td> </tr>";
    $("#tblUser tbody").append(newRow); }); </script>

    Index

    @using (Html.BeginForm("Index", "User", FormMethod.Post, new { enctype = "multipart/form-data",id="myform" }))
    {
        @Html.AntiForgeryToken()
        <hr />
        <table border="1" cellpadding="10" id="tblUser">
            <tr>
                <th>UserId</th>
                <th>UserName</th>
                <th>UserRole</th>
                <th>IsActive</th>
                <th>IsNewUser</th>
                <th colspan="2">Actions</th>
            </tr>
            @foreach (var item in Model.users)
            {
                <tr>
                    <td>@item.UserId</td>
                    <td>@item.UserName</td>
                    <td>@item.UserRole</td>
                    <td>@item.IsActive</td>
                    <td>@item.IsNewUser</td>
                    <td><button type="button" class='delete' >Del</button></td>
                </tr>
            }
        </table>
        <input id="JSONText" name="jsontext" value="" hidden="hidden" />
        <br />
        <br />
        <input type="button" name="btnSumit" value="SaveToDatabase" onclick="sub()" />
        <br />
    }
        <script>
            $(".delete").click(function (e) {
                $(this).closest("tr").remove();
            })
            function sub(){
                var tr;
                var table = document.getElementById("tblUser");
                var num = document.getElementById("tblUser").rows.length;
                var dataArray = new Array();
                for (var i = 1; i < num; i++) {
                    date = new Object();
                    tr = table.rows[i];
                    date.Id = tr.cells[0].innerHTML;
                    date.Name = tr.cells[1].innerHTML;
                    date.Role = tr.cells[2].innerHTML;
                    date.Active = tr.cells[3].innerHTML;
                    date.NewUser = tr.cells[4].innerHTML;
                    dataArray.push(date);
                }
                document.getElementById('JSONText').value = JSON.stringify(dataArray);
                myform.submit();
            }
        </script>

    Controller

            [HttpPost]
            public ActionResult Index(UserModel users)
            {
                var a = Request.Form["jsontext"];
                JArray jArray = (JArray)JsonConvert.DeserializeObject(a);
                List<User> ulst = new List<User>();
                for(int i = 0; i < jArray.Count; i++)
                {
                    User user = new User();
                    user.UserId = (int)jArray[i]["Id"];
                    user.UserName = jArray[i]["Name"].ToString();
                    user.UserRole= jArray[i]["Role"].ToString();
                    user.IsActive = (bool)jArray[i]["Active"];
                    user.IsNewUser = (bool)jArray[i]["NewUser"];
                    ulst.Add(user);
                }
                //model.users = Here i want to get all the records which are the table
                return View();
    
            }

    Here is the result.

    Best regards,

    Yihui Sun

    Monday, July 27, 2020 8:47 AM