简体   繁体   中英

How to Pass data to controlller- one to many relationship .net core

I want to save theese data to the database

there is a two models . Athlete and Client

relationship is client has many Athlete

I want to know how to pass client details with Athlete details

public class Athlete
{
    [Key]
    public string ID { get; set; } = Guid.NewGuid().ToString();
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Description { get; set; }
    public Client Client { get; set; }
}



public class Client
{
    [Key]
    public string ID { get; set; } = Guid.NewGuid().ToString();
    public string CompanyName { get; set; }
    public string ApplicationUserId { get; set; }
    public List<Athlete> Athletes { get; set; }
}

//THis is HTML Form

<li>
        <label>First Name</label>
        @Html.TextBoxFor(x => x.FirstName, new { maxlength = 100 })
    </li>
    <li>
        <label>Last Name</label>
        @Html.TextBoxFor(x => x.LastName, new { maxlength = 100 })
    </li>
    <li>
        <label>Email</label>
        @Html.TextBoxFor(x => x.Email, new { maxlength = 100 })
    </li>
    <li>
        <label>Address Line 3</label>
         @Html.TextBoxFor(x => x.AddressLine3, new { maxlength = 100 })
    </li>
</ul>

just do this :

        .
        .
        .
        <li>
            <label>CompanyName</label>
            @Html.TextBoxFor(x => x.Client.CompanyName )
        </li>
        <li>
            <label>ApplicationUserId</label>
            @Html.TextBoxFor(x => x.Client.ApplicationUserId)
        </li>
       <li>
           //and another field you want...
        </li>
    </ul>

I hope it has been helpful .

You may use Begincollectionitemcore package. Demo can found here . Sample code is below In Controller

        public IActionResult Index()
        {
            return View();
        }
        [AjaxOnly]
        [ResponseCache(NoStore = true, Duration = 0)]
        public IActionResult NewItem()
        {
            return PartialView("_CollectionPartial", new OrderItemModel());
        }

In Views

    @foreach (var item in Model.OrderItemModel)
                    {
                        <partial name="NewItem.cshtml" model="item" />
                    }
    <script>
     $('#btnAddMore').click(function () {
                $.ajax({
                    url: '/Home/NewItem',
                    success: function (html) {
                        $('#collectionItems').append(html);
                    }
                });
            });

</script>

Detail Partial page

@using HtmlHelpers.BeginCollectionItemCore;
@model BeginCollectionItemCoreDemo.ViewModels.OrderItemModel

    <div class="form-horizontal well">
        @using (Html.BeginCollectionItem("OrderItems"))
        {
            <div class="form-group">
                <label asp-for="Id" class="col-md-2 control-label"></label>
                <div class="col-md-10">
                    <input asp-for="Id" class="form-control" />
                    <span asp-validation-for="Id" class="text-danger" />
                </div>
            </div>
    }

I want to know how to pass client details with Athlete details

You could use the javascript to add multiple Athlete details when adding a client detail and update the database in the controller like below:

Model

public class Client
{
    [Key]
    public string ID { get; set; } = Guid.NewGuid().ToString();
    public string CompanyName { get; set; }
    public string ApplicationUserId { get; set; }
    public List<Athlete> Athletes { get; set; }
}
public class Athlete
{
    [Key]
    public string ID { get; set; } = Guid.NewGuid().ToString();
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Description { get; set; }
    //public Client Client { get; set; }
}

View

@model WebApplication1.Models.Clients.Client

<div class="row">
  <div class="col-md-4">
    <form asp-action="Create">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="CompanyName" class="control-label"></label>
            <input asp-for="CompanyName" class="form-control" />
            <span asp-validation-for="CompanyName" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="ApplicationUserId" class="control-label"></label>
            <input asp-for="ApplicationUserId" class="form-control" />
            <span asp-validation-for="ApplicationUserId" class="text-danger"></span>
        </div>

        <div class="form-group">
            <label asp-for="Athletes" class="control-label"></label>
            <table id="tblAthletes" class="table" cellpadding="0" cellspacing="0">
                <thead>
                    <tr>
                        <th style="width:150px">First Name</th>
                        <th style="width:150px">Last Name</th>
                        <th style="width:150px">Email</th>
                        <th style="width:150px">Description</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="item-list">
                    <tr>
                        <td><input type="text" asp-for="Athletes" class="items" name="Athletes[0].FirstName" /></td>
                        <td><input type="text" asp-for="Athletes" class="items" name="Athletes[0].LastName" /></td>
                        <td><input type="text" asp-for="Athletes" class="items" name="Athletes[0].Email" /></td>
                        <td><input type="text" asp-for="Athletes" class="items" name="Athletes[0].Description" /></td>
                        <td><input type="button" id="btnAdd" value="Add" /></td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </form>
  </div>
</div>

@section Scripts
{
 <script type="text/javascript">
    $("#btnAdd").click(function (e) {

        e.preventDefault();
        var i = ($(".items").length) / 4;
        var n = '<tr>' + '<td><input type="text" class="items" name="athletes[' + i + '].FirstName" /></td>' +
            '<td><input type="text" class="items" name="athletes[' + i + '].LastName" /></td>' +
            '<td><input type="text" class="items" name="athletes[' + i + '].Email" /></td>' +
            '<td><input type="text" class="items" name="athletes[' + i + '].Description" /></td>' +'</tr>';

        $("#item-list").append(n);

 </script>
}

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create( Client client)
 {
        if (ModelState.IsValid)
        {
            _context.Add(client);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(client);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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