bind values to model on form submitting

Hi.
How can i bind selected values to model on form submitting for next controls:
- ejs-checkbox
- ejs-listview (with checkbox selection)

For example, i'm using ejs-dropdownlist control value attribute to get selected value successfully, but ejs-listview does not have this.
In case of ejs-checkbox i'm trying to use value attribute to get selection, but without success

3 Replies

SS Subha Shree Ramanathan Syncfusion Team April 24, 2018 02:12 PM UTC

Hi Alex, 
 
Thanks for your interest in Syncfusion components. 
 
We have validated the reported scenario and find the details as below. 
 
Query 1: To bind selected values of ejs-checkbox to model on form submit 
 
We can achieve the scenario by using ejs-checkbox in ASP .Net Core. On form submit, the defined checkbox values can be passed to the controller along with their defined name attribute value as like key-value pair. Please find the below code example 
 
[View] 
  
<form asp-controller="Home" asp-action="Index" method="post">  
    <ejs-checkbox id="cbox2" name="Sport" value="Cricket" label="Cricket" checked="true"></ejs-checkbox>  
    <ejs-checkbox id="cbox3" name="Sport" value="Hockey" label="Hockey" checked="true"></ejs-checkbox>  
    <ejs-checkbox id="cbox4" name="Sport" value="Tennis" label="Tennis"></ejs-checkbox>  
    <ejs-checkbox id="cbox1" name="Sport" value="Basketball" label="Basketball"></ejs-checkbox>  
    <ejs-button id="primarybtn" content="Submit" isPrimary="true"></ejs-button>  
</form>  
  
  
[Controller] 
  
[HttpPost]          
public IActionResult Index(SportModel model)  
{  
    //Here you can get the selected checkbox values.  
    var selectedChkBxValues = model.Sport;  
  
    //Your code here.  
  
}  
  
//...  
  
public class SportModel  
{  
    public List<string> Sport { get; set; }  
} 
  
 


Query 2: To bind selected values of ejs-listview to model on form submit  
 
We can achieve your requirement, in ListView using getSelectedItems() method, which is used to get the selected items from the ListView control. For your kind information, the ListView control is not an form control, we have to use the methods to retrieve the selected items values. 
 
 
Below tables represents the values returned by the getSelectedItems method. 
 
SelectedItem – An Interface used when checkbox is disabled. 
SelectedCollection – An Interface used when checkbox is enabled. 
 
SelectedItem: 
 
 
Return Values 
Return Type 
Description 
data 
Object | string[] 
It denotes the Selected Item dataSource JSON object. 
Here We can retire id, text etc.  
Item 
HTMLElement | Element 
It denotes the Selected Item list element. 
text 
string 
It denotes the Selected Item text. 
 
SelectedCollection: 
 
Return Values 
Return Type 
Description 
Data 
Object | Object[] | string[] 
It denotes the Selected Item dataSource JSON object or object collection. 
Here We can retire id, text etc. 
Item 
HTMLElement | Element[] | HTMLCollection 
It denotes the Selected Item list element or element collection. 
text 
string | string[] 
It denotes the Selected Item text data or collection. 
 
In your case, SelectedCollection will be used, as we are using checklist and we can achieve your requirement by using ‘text’ parameter returned by the  getSelectedItems method. 
 
[Code Snippet] 
 
[Lists.cshtml] 
 
 Here we get and update the selected items in textbox, which is retrieved back in controller through name attribute of textbox element. 
 
 
@{ 
  ViewBag.Title = "Welcome to My Index Page"; 
} 
 
<h1>Wecome to Forms Page</h1><br /> 
 
<form asp-controller="MyCal" method="post"> 
  <ejs-listview id="list" dataSource="@ViewBag.dataSource" showCheckBox="true" showHeader="true" headerTitle="Types Of Art"></ejs-listview> 
  <br /> 
  <label for="art">Type of art you are in to: </label> 
  <input id="art" type="text" name="art" /> 
  <br /> 
  <input type="submit" id="button" value="Submit" formaction="GetValues" /> 
 
</form> 
 
<h2 style="color:crimson; background-color:darksalmon; padding:10px;"> 
  @ViewBag.Result 
</h2> 
 
<script> 
 
  document.getElementById('button').addEventListener('click', function () { 
      // Obtaining Listview Instance 
      var listviewInstance = document.getElementById('list').ej2_instances[0]; 
      var texts = ""; 
 
      for (var i = 0; i < listviewInstance.getSelectedItems().text.length; i++) { 
          // Assigning each value selected in the listview 
          texts = texts + listviewInstance.getSelectedItems().text[i] + ", "; 
      } 
 
      // Removes extra comma 
      texts = texts.replace(/(^,)|(, $)/g, ""); 
 
      // Assigning listview value to text box 
      var textbox = document.getElementById('art'); 
      textbox.value = texts; 
 
  }) 
 
</script> 
 
 
 
[MyCalController.cs] 
 
using System; 
using System.Collections.Generic; 
using Microsoft.AspNetCore.Mvc; 
using WebApplication2.Controllers; 
 
namespace Listview.Controllers 
{ 
    public class MyCalController : Controller 
    { 
        // GET: /<controller>/ 
        public IActionResult Lists() 
        { 
            //define the array of JSON 
            List<object> data = new List<object>(); 
            data.Add(new { text = "Artwork", id = "01" }); 
            data.Add(new { text = "Abstract", id = "02" }); 
            data.Add(new { text = "Modern Painting", id = "03" }); 
            data.Add(new { text = "Oil Painting", id = "04" }); 
 
            ViewBag.dataSource = data; 
            return View(); 
        } 
 
        [HttpPost] 
        public IActionResult GetValues() 
        { 
            string value  = HttpContext.Request.Form["art"]; 
            ViewBag.Result = value; 
            return View("Values"); 
        } 
    } 
} 

 
Note: To view the demo List.cshtml file type in URL ‘http://localhost:[Your Port]/MyCal/Lists’ 
 
For your convenience, we have prepared a sample using our ListView control in forms which will submit the checked values from the ListView to another page. 
 
 
Please let us know if you need further assist on this. 
 
Thanks, 
Subha Shree D.R 



BW bwmmc March 16, 2025 03:07 AM UTC

Yuck. Sorry, but this is a horrible way to save data back to the controller. You're circumventing all the great features of MVC and Razor that could perform the above in only a single line of code on both the client and server and instead are doing everything manually in Javascript and then capturing the request body, like 1990s PHP. You guys need to start binding the listview component in the view to a form element so that it can get easily posted back.



PM Prasanth Madhaiyan Syncfusion Team March 17, 2025 07:29 AM UTC

Hi Bwmmc,


Instead of manually setting the value of the input field in JavaScript and handling the request body manually, you can bind the ListView to a model and leverage model binding in ASP.NET Core to handle the post back seamlessly.

Step 1: Create a Model

  • Create a model to hold the selected values:

[Models/ArtModel.cs]

namespace CoreSample.Models
{
    public class ArtModel
    {
        public List<string> SelectedArt { get; set; }
    }
}

Step 2: Update the Controller

[HomeController .cs]

...

namespace CoreSample.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            LoadData(); // Load data when rendering the Index page
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [HttpPost]
        public IActionResult GetValues(ArtModel model)
        {
            if (model.SelectedArt != null && model.SelectedArt.Any())
            {
                ViewBag.Result = string.Join(", ", model.SelectedArt);
            }
            else
            {
                ViewBag.Result = "No items selected";
            }
            LoadData(); // Load data again when rendering the view after form submission

            // Return the same Index view
            return View("Index", model);
        }

        private void LoadData()
        {
            List<object> data = new List<object>
            {
                new { text = "Artwork", id = "01" },
                new { text = "Abstract", id = "02" },
                new { text = "Modern Painting", id = "03" },
                new { text = "Oil Painting", id = "04" }
            };

            ViewBag.dataSource = data;
        }

    }
}
...

Step 3: Update the View

Use the Html.HiddenFor helper to send the selected values automatically with the form submission.

[Index.cshtml]

@{
    ViewBag.Title = "Welcome to My Index Page";
}
@using Syncfusion.EJ2

@model CoreSample.Models.ArtModel

<h1>Welcome to Forms Page</h1>
<br />

<form asp-controller="Home" asp-action="GetValues" method="post">
    <ejs-listview id="list" dataSource="@ViewBag.dataSource" showCheckBox="true" showHeader="true" headerTitle="Types Of Art"></ejs-listview>

    @Html.HiddenFor(model => model.SelectedArt)

    <br />
    <input type="submit" value="Submit" />
</form>

<h2 style="color:crimson; background-color:darksalmon; padding:10px;">
    @ViewBag.Result
</h2>

<script>
    document.querySelector('form').addEventListener('submit', function () {
        var listviewInstance = document.getElementById('list').ej2_instances[0];
        var selectedItems = listviewInstance.getSelectedItems().text;
        document.querySelector('[name="SelectedArt"]').value = selectedItems.join(',');
    });
</script>


For your reference, we have attached the sample and screenshots. 

Sample: Attached as a zip file. 

Screenshots: 

Before form submission 
After form submission

Check out the attached sample and let us know if you need any further assistance.

Regards,

Prasanth Madhaiyan.


Attachment: CoreListViewSample_c73c4c54.zip

Loader.
Up arrow icon