0

This is my first time working with web development and have decided to use 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.

My example:

Model Contract contains an object of type List<Variable>. When I create the Contract from the view I want to be able to create variables from the same view for the given 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.

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

4
  • OK, I see. Apparently the scaffolding process doesn't attempt to recursively walk through the contract and create scaffolding for related entities, which kinda does make sense. Naturally, nothing prevents you from adding this additional "scaffolding" yourself. Commented Jan 7, 2021 at 17:11
  • Yes but I am not able to have two models in a single view Commented Jan 7, 2021 at 17:20
  • how do you scaffold this? if you're an asp.net core mvc beginner, why not try writing all the code yourself first? I've done several projects with asp.net core but really never used such a feature (scaffolding view). Commented Jan 7, 2021 at 17:23
  • You should only need a single "View Model" object that contains all of the data you need to materialize your view. But you're going to have to write some of this code yourself; the scaffolding system is very basic, and does not have the capability of meeting the requirements you describe on its own. Commented Jan 7, 2021 at 17:23

1 Answer 1

2

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:

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: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.