8

I'm working in asp.net core inside a MVC application. I'm using the scaffolding feature that creates the views and controller based on a model. Below is the model that i'm using:

class ShoppingList
{
    public int ShoppingListId { get; set; }
    public string Name { get; set; }
    public List<string> ListItems { get; set; }            
}

The form that displays to the user via the view only displays the field for Name. I would like the form to be able to show a field for a list item, and then if the user wants to add another list item they can hit a button to add another field to do so. They at run time decide how many shopping list items they want to add.

Here is the razor cshtml form i'm using:

<form asp-action="Create">
     <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
           <label asp-for="Name" class="control-label"></label>
           <input asp-for="Name" class="form-control" />
           <span asp-validation-for="Name" class="text-danger"></span>
        </div>
     <div class="form-group">
     <input type="submit" value="Create" class="btn btn-default" />
     </div>
</form>

Is there an easy way to do this? I don't want to have to hard code a number.

conterio
  • 1,087
  • 2
  • 12
  • 25
  • use jQuery to add an input element to the DOM. – Shyju Oct 20 '17 at 17:14
  • the issue I get with that is, when I submit the form the newly added elements don't get sent with the submit. @Shyju – conterio Oct 20 '17 at 17:15
  • it does as long us the names matches with what the model binder is looking for. Share the code what you tried – Shyju Oct 20 '17 at 17:17
  • @JeremyConterio if you are using Razor views I will have an answer for you. – Jared Oct 20 '17 at 17:17
  • @Jared I'm using razor pages. I'll updated my question to show the form i'm using. – conterio Oct 20 '17 at 17:22
  • You got 2 different answers, one adding Input fields to be completed and another listing your selected items, can you clarify the question a little bit? – Ermir Beqiraj Oct 20 '17 at 18:00
  • @Jared i'm trying to create data now show it. I want to submit a form with x amount of shopping list items that is determined by the end user. – conterio Oct 20 '17 at 18:16
  • I wish that the scaffolding knew to do this automatically, I put in a feature request with the .net core scaffolding team – conterio Oct 20 '17 at 18:21

2 Answers2

14

If you want to allow the user to add a new form element on the client side you need to use javascript to update the DOM with the new element you want to add. To list the existing items you may use editor templates. Mixing these 2 will give you a dynamic form. The below is a basic implementation.

To use editor templates, we need to create an editor template for the property type. I would not do that for string type which is more like a generic one. I would create a custom class to represent the list item.

public class Item
{
    public string Name { set; get; }
}
public class ShoppingList
{
    public int ShoppingListId { get; set; }
    public string Name { get; set; }
    public List<Item> ListItems { get; set; }

    public ShoppingList()
    {
        this.ListItems=new List<Item>();
    }
}

Now, Create a directory called EditorTemplates under ~/Views/YourControllerName or ~/Views/Shared/ and create a view called Item.cshtml which will have the below code

@model  YourNameSpaceHere.Item
<input type="text" asp-for="Name" class="items" />

Now in your GET controller, create an object of the ShoppingList and send to the view.

public IActionResult ShoppingList()
{
    var vm = new ShoppingList() {  };
    return View(vm);
}

Now in the main view, All you have to do is call the EditorFor method

@model YourNamespace.ShoppingList
<form asp-action="ShoppingList" method="post">
    <input asp-for="Name" class="form-control" />
    <div class="form-group" id="item-list">
        <a href="#" id="add">Add</a>
        @Html.EditorFor(f => f.ListItems)
    </div>
    <input type="submit" value="Create" class="btn btn-default" />
</form>

The markup has an anchor tag for adding new items. So when user clicks on it, we need to add a new input element with the name attribute value in the format ListItems[indexValue].Name

$(function () {

   $("#add").click(function (e) {
       e.preventDefault();
       var i = $(".items").length;
       var n = '<input type="text" class="items" name="ListItems[' + i + '].Name" />';
       $("#item-list").append(n);
   });

});

So when user clicks it adds a new input element with the correct name to the DOM and when you click the submit button model binding will work fine as we have the correct name attribute value for the inputs.

[HttpPost]
public IActionResult ShoppingList(ShoppingList model)
{
    //check model.ListItems
    // to do : return something
}

If you want to preload some existing items (for edit screen etc), All you have to do is load the ListItems property and the editor template will take care of rendering the input elements for each item with correct name attribute value.

public IActionResult ShoppingList()
{
    var vm = new ShoppingList();
    vm.ListItems = new List<Item>() { new Item { Name = "apple" } }
    return View(vm);
}
Shyju
  • 214,206
  • 104
  • 411
  • 497
-1

First this is you must have a public accessor to your ShoppingList class.

So, public class ShoppingList.

Next is your view will need the following changes.

@model ShoppingList

<h1>@Model.Name</h1>
<h2>@Model.ShoppingListId</h2>
foreach(var item in Model.ListItems)
{
    <h3>@item</h3>
}

So, the above code is roughly what you are looking for. In Razor you can accessor the models variables by using the @model at the top of the view. But one thing you need to note is if your model is in a subfolder you'll need to dot into that.

Here's an example: @model BethanysPieShop.Models.ShoppingCart.

Here BethanysPieShop is my project name, Models is my folder the ShoppingCart class is in.

Jared
  • 394
  • 4
  • 15