0

How can I turn a text input separated by comma in html into a list of a model that I created and add the values into a sql-table

Models

public class Person
{
    [Key]
    public string PersonId { get; set; }
    public string Name { get; set; }
    [DefaultValue(0)]
    public int Set1 { get; set; }
    [DefaultValue(0)]
    public int Set2 { get; set; }
    [DefaultValue(0)]
    public int Set3 { get; set; }
    public string DepartmentId {  get; set; }
    public Department Department { get; set; }
}

public class Department
{
    [Key]
    public string DepartmentId { get; set; }
    public string? DepartmentName { get; set; }
    public List<Person> Persons { get; set; }
}

View Model

 public class CreateDepartmentViewModel
 {
     public string DepartmentName { get; set; }
     public List<Person> Persons { get; set; }
 }

Cshtml Page

@model BTAnCaWeb.ViewModels.CreateDepartmentViewModel
<div class="container mb-3">
    <div class="row pt-4">
        <div class="col-6">
            <h2 class="text-primaary">
                Thêm phòng ban mới
            </h2>
        </div>
    </div>
</div>
<form method="post" action="Create">
    <div class="mb-3">
        <label for="DepName" class="form-label">Department Name</label>
        <input type="text" class="form-control" asp-for="@Model.DepartmentName" id="DepName">
    </div>
    <div class="mb-3">
        <label for="Persons" class="form-label">People in department</label>
        <input type="text" class="form-control" asp-for="@Model.Persons" id="Persons" />
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

Example input

I haven't found anything relevant on stack overflow or google yet

1
  • Hows your input looks like? could please show us? Usually we could use Split(',') to seperate the value by comma. Commented Jul 3 at 8:36

1 Answer 1

0

How can I turn a text input separated by comma in html into a list of a model that I created and add the values into a sql-table

According to your scenario and description along with the shared code snippet, to turn a comma-separated text input into a list of Person objects and add these values into a SQL table, you need to process the input in your controller method.

In order to implement that, you need to follow few steps. First of all, Update the CreateDepartmentViewModel to accept a string input for the persons.

Then, update your view to bind to this new string property.

Finally, within your controller, split the string into individual names, create Person objects, and save them to the database along with the department.

Let's have a look in practice, how we could achieve that:

Updated View Model:

public class CreateDepartmentViewModel
{
    public string DepartmentName { get; set; }
    public string PersonNames { get; set; } 
    public List<Person> Persons { get; set; }
}

Note: The sole purpose of new property (PersonNames) is to hold comma-separated names.

Controller:

[HttpPost]
public async Task<IActionResult> Create(CreateDepartmentViewModel model)
{
    var department = new Department
    {
        DepartmentId = Guid.NewGuid().ToString(),
        DepartmentName = model.DepartmentName,
        Persons = new List<Person>()
    };

    if (!string.IsNullOrWhiteSpace(model.PersonNames))
    {
        var names = model.PersonNames.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

        foreach (var name in names)
        {
            var person = new Person
            {
                PersonId = Guid.NewGuid().ToString(),
                Name = name.Trim(),
                DepartmentId = department.DepartmentId
            };
            department.Persons.Add(person);
        }
    }

    _context.Departments.Add(department);
    await _context.SaveChangesAsync();

    return RedirectToAction("Create");

 
}

Note: So within the controller what I did is, in model.PersonNames I have splited into individual names using Split(). Then each name is trimmed and used to create a Person object.

Afterwords, each Person object is added to the Persons list of the Department. Finally, the Department (along with its associated Persons) is saved to the database. You could include any validation stuff if you need.

View:

@model CreateDepartmentViewModel

<div class="container mb-3">
    <div class="row pt-4">
        <div class="col-6">
            <h2 class="text-primaary">
                Add New Department
            </h2>
        </div>
    </div>
</div>
<form method="post" action="/Department/Create">
    <div class="mb-3">
        <label for="DepName" class="form-label">Department Name</label>
        <input type="text" class="form-control" asp-for="DepartmentName" id="DepName">
    </div>
    <div class="mb-3">
        <label for="Persons" class="form-label">People in Department</label>
        <input type="text" class="form-control" asp-for="PersonNames" id="Persons" />
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

Note: Make sure to bind the new property PersonNames to the input field.

Output:

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Note: Please refer to this official document, if you want to learn additional details.

Not the answer you're looking for? Browse other questions tagged or ask your own question.