简体   繁体   English

如何从 ASP.NET Core MVC 中的视图创建 object

[英]How to create an object from the view in ASP.NET Core MVC

This is my first time working with web development and have decided to use ASP.NET Core MVC.这是我第一次使用 web 开发并决定使用 ASP.NET Core MVC。

When I create a new item for the model from the View, I want to also be able to create the model that is being used by the main model.当我从视图中为 model 创建新项目时,我还希望能够创建主 model 正在使用的 model。

My example:我的例子:

Model Contract contains an object of type List<Variable> . Model Contract包含一个List<Variable>类型的 object 。 When I create the Contract from the view I want to be able to create variables from the same view for the given contract.当我从视图创建Contract时,我希望能够从给定合同的同一视图创建变量。

This is the code being generated from core scaffold这是从核心脚手架生成的代码

    <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">
        <label asp-for="Content" class="control-label"></label>
        <textarea oninput="auto_grow(this)" , style="width:90%; min-height: 500px; resize: vertical; overflow: auto" asp-for="Content" class="form-control">
            
        </textarea>
        <span asp-validation-for="Content" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Descrption" class="control-label"></label>
        <input asp-for="Descrption" class="form-control" />
        <span asp-validation-for="Descrption" class="text-danger"></span>
    </div>
    <div class="form-group">
        <input type="submit" value="Create" class="btn btn-primary" />
    </div>
</form>

As you can see other parameters of the Contract model are being shown except the List[Variable] and I am not sure how the best way to add it is.如您所见,除了 List[Variable] 之外,还显示了合同 model 的其他参数,我不确定添加它的最佳方法是什么。

public class Contract
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Content { get; set; }

    public List<Variable> Variable { get; set; }

    public string Descrption { get; set; }
}

I'm sorry if there are missing details.如果有遗漏的细节,我很抱歉。 Feel free to ask questions I will be happy to provide随时提出问题,我很乐意提供

You can use a table in form to show your Variable,and when form post,post the Contract with Variable to action.Here is a demo:您可以在表单中使用表格来显示您的变量,并在表单发布时,将带有变量的合同发布到操作。这是一个演示:

Controller: Controller:

public IActionResult TestContract()
        {
           
            return View();
        }
        public IActionResult Create(Contract c)
        {
            //passing Contract with List<Variable> to the action,you can do something you want here
            return Ok();
        }

Variable:多变的:

public class Variable
    {
        public int VariableId { get; set; }
        public string VariableName { get; set; }

    }

View:看法:

    <form asp-action="Create" id="myform">
    <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">
        <label asp-for="Content" class="control-label"></label>
        <textarea oninput="auto_grow(this)" , style="width:90%; min-height: 500px; resize: vertical; overflow: auto" asp-for="Content" class="form-control">
            
        </textarea>
        <span asp-validation-for="Content" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Descrption" class="control-label"></label>
        <input asp-for="Descrption" class="form-control" />
        <span asp-validation-for="Descrption" class="text-danger"></span>
    </div>
    <div>
        <table id="myTable">
            <thead>
                <tr>
                    <th scope="col">VariableId</th>
                    <th scope="col">VariableName</th>

                </tr>
            </thead>
            <tbody>
               
            </tbody>
        </table>
    </div>
    
    <div class="row final-mile__step-control">
        <div class="col justify-content-center">
            <button type="button" onclick="Add()">Add Variable</button>
        </div>
    </div>
    <div>
        <input type="submit" value="Submit" />
    </div>
</form>
<script>
        function Add() {
            $('#myTable > tbody').append('<tr><td><input name="VariableId" class="form-control" required="required" placeholder="VariableId" /><span class="field-validation-valid text-danger" data-valmsg-for="VariableId" data-valmsg-replace="true"></span></td>' +
                '<td> <input name="VariableName" class="form-control"  required="required"  placeholder="VariableName" /><span class="field-validation-valid text-danger" data-valmsg-for="VariableName" data-valmsg-replace="true"></span></td>' +
                '<td><input type="button" onclick="Delete(this)" value="Delete" /></td ></tr > ');
        };
        function Delete(d) {
            $(d).closest("tr").remove();
        };
        $('#myform').submit(function () {
            var count = 0;
            $('#myTable tbody tr').each(function () {
                $(this).find("input[name='VariableId']").attr("name", "Variable[" + count + "].VariableId");
                $(this).find("input[name='VariableName']").attr("name", "Variable[" + count + "].VariableName");
                count++;
            });
            return true; // return false to cancel form action
        });
        $(".submit").on('click', function () {
            var list = [];
            $('#myTable tbody tr').each(function () {
                var obj = {};
                obj.FirstName = $(this).find("td").find("input[name='FirstName']").val();
                obj.LastName = $(this).find("td").find("input[name='LastName']").val();
                obj.Dob = $(this).find("td").find("input[name='Dob']").val();
                list.push(obj);
            });
            $.ajax({
                type: "POST",
                url: '@Url.Action("TestEmployee", "Test1")',
                contentType: "application/json",
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                data: JSON.stringify(list)
            }).done(function (data) {

            });

        });
    </script>

result:结果: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM