如何在带有JavaScript和C#的ASP.NET Core 3.1 MVC中使用ViewModel动态添加到列表 [英] How to dynamically add to list with ViewModel in ASP.NET Core 3.1 MVC with JavaScript and C#

查看:60
本文介绍了如何在带有JavaScript和C#的ASP.NET Core 3.1 MVC中使用ViewModel动态添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JavaScript在ViewModel中动态添加到列表属性.每当我提交表单时,发布控制器中的列表中就没有任何项目.我试图使用像这样的剃刀语法将其添加到JavaScript函数中的列表中:

I am trying to dynamically add to a list property in my ViewModel using JavaScript. Whenever I submit my form, there are no items in the list in the post controller. I have tried to add to the list inside the JavaScript function using razor syntax like so:

@{
    Model.Contacts.Add(new Contact { ID = 1, FirstName = "Tester" })
}

只是看看我是否还能在列表中找到一个项目.我还在页面顶部完成了该操作,以查看它是否仅是因为它在JavaScript中.但是,当我提交表单时,发生了同样的事情,列表中没有项目.我不知道是否需要创建API才能提交数据,但是Company属性会在其中提交数据.我希望能够在不必创建API的情况下提交这两个属性.我不知道是否可以使用特殊的剃刀语法或类来实现这一目标.请帮忙!谢谢.

Just to see if I could even get a item in the list. I've also done it at the top of the page to see if it was just because it was in JavaScript. However when I submitted the form the same thing happened, no items in the list. I don't know if I need to create an API in order to submit the data, but the Company property submits with data in it. I would like to be able to submit both properties without having to create an API. I don't know if there's a special razor syntax or class that I can use to achieve this. Please help! Thank you.

创建公司页面

ViewModel:

ViewModel:

public class CompanyViewModel
    {
        public Company Company { get; set; }
        public List<Contact> Contacts { get; set; }

        public CompanyViewModel()
        {
            this.Contacts = new List<Contact>();
        }
    }

控制器:

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

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(CompanyViewModel companyView)
        {
            if (companyView.Company != null)
            {
                _context.Add(companyView.Company);
                if (companyView.Contacts != null)
                    _context.Contacts.AddRange(companyView.Contacts);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(companyView);
        }

查看:

@model CheckbookRegister.Models.CompanyViewModel

@{
    ViewData["Title"] = "Create";
}

<h1>Create Company</h1>
<hr />
<form asp-action="Create">

    <!-- Omitted for brevity -->

    <div class="row justify-content-between">
        <h4 class="col mb-0 align-self-end">Contacts</h4>
        <div class="col-md-auto text-right mt-2">
            <a class="col btn btn-sm btn-outline-success px-4" id="add" href="#" onclick="addContact()">Add</a>
        </div>
    </div>
    <table class="table mt-2" id="contactsTable">
        <thead>
            <tr>
                <th><label asp-for="@Model.Contacts.First().FirstName" class="control-label"></label></th>
                <th><label asp-for="@Model.Contacts.First().LastName" class="control-label"></label></th>
                <th><label asp-for="@Model.Contacts.First().Email" class="control-label"></label></th>
                <th><label asp-for="@Model.Contacts.First().PhoneNumber" class="control-label"></label></th>
                <th><label asp-for="@Model.Contacts.First().WorkPhoneNumber" class="control-label"></label></th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <div class="form-group">
        <input type="submit" value="Create" class="btn btn-primary"/>
    </div>
</form>

@section Scripts{ 
    <script type="text/javascript">
        var count = 0;
        function addContact() {
            var table = document.querySelector("tbody");
            table.insertAdjacentHTML("beforeend", "<tr>" +
                "<td>" +
                "<input asp-for='Model.Contacts[" + count + "].FirstName' class='form-control'/>" +
                "<span asp-validation-for='Model.Contacts[" + count + "].FirstName' class='text-danger'></span >" +
                "</td>" +
                "<td>" +
                "<input asp-for='Model.Contacts[" + count + "].LastName' class='form-control'/>" +
                "<span asp-validation-for='Model.Contacts[" + count + "].LastName' class='text-danger'></span >" +
                "</td>" +
                "<td>" +
                "<input asp-for='Model.Contacts[" + count + "].Email' class='form-control'/>" +
                "<span asp-validation-for='Model.Contacts[" + count + "].Email' class='text-danger'></span >" +
                "</td>" +
                "<td>" +
                "<input asp-for='Model.Contacts[" + count + "].PhoneNumber' class='form-control'/>" +
                "<span asp-validation-for='Model.Contacts[" + count + "].PhoneNumber' class='text-danger'></span >" +
                "</td>" +
                "<td>" +
                "<input asp-for='Model.Contacts[" + count + "].WorkPhoneNumber' class='form-control'/>" +
                "<span asp-validation-for='Model.Contacts[" + count + "].WorkPhoneNumber' class='text-danger'></span >" +
                "</td>" +
                "<td>" +
                "<button type='button' class='btn btn-sm btn-outline-danger' onclick='deleteContact(this)'>Delete</button>" +
                "</td>" +
                "</tr>");
            count++;
        }
        function deleteContact(button) {
            button.closest("tr").remove();
        }
    </script>
}

推荐答案

因此,要一个接一个地添加联系人,您的视图模型应该是联系人,并且您的表单应该看起来像这样,除了使用您的联系人类属性而不是电子邮件密码.

So to add contact one by one your view model should be contact and your form should look like this except instead of email password use your contact class properties.

<form asp-controller="Demo" asp-action="RegisterInput" method="post">
    Email:  <input asp-for="Email" /> <br />
    Password: <input asp-for="Password" /><br />
    <button type="submit">Register</button>
</form>

您的控制器应接受联系人类别作为参数.这将适用于一个接一个的添加联系人.

You controller should accept contact class as param. This will work for adding contact one by one.

对于多个联系人,将当前使用的视图模型与联系人列表一起使用.然后在您的视图中对该列表中的每个属性使用,然后为每个联系人属性及其值添加输入.

For multiple contacts, use the same view model that you currently have with a list of contacts. Then use for each on that list In your view and then add the inputs for each contact property and it’s values.

当您必须添加新联系人时,基本上是通过js的添加按钮的点击事件为新联系人生成html.

When you have to add a new contact basically generate html for a new contact on click event of an add button via js.

按照此问题进行操作,您将走在正确的轨道上:如何使用Razor和.NET Core将项目添加到ViewModel的列表中?

Follow this question and you’ll be on the right track: How to add an item to a list in a ViewModel using Razor and .NET Core?

这篇关于如何在带有JavaScript和C#的ASP.NET Core 3.1 MVC中使用ViewModel动态添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆