Как сохранить пользовательскую модель в ASP.NET MVC 5 с Entity Framework 6? - PullRequest
0 голосов
/ 02 декабря 2018

Дизайн:

enter image description here

Код:

@using (Html.BeginForm())
{
    ... code block ...

          // BULK INSERT OF COST PER WEIGHT
            @foreach (var item in ViewBag.WeightId)
            {
                <input type="hidden" id="WeightId" name="WeightId" value="@item.Value" />

                <label for="WeightId">@item.Text kg</label>
                @Html.Editor("Cost", new { htmlAttributes = new {  data_weight_id = @item.Value } })
            }

        ... code block ...
}

Я не использую автоматически созданную модель для сохранения данных.Я использую цикл for для создания списка весов и соответствующих текстовых полей.

Моя пользовательская модель:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using CouriersHub.DAL;

namespace CouriersHub.Models
{
    public class CostWeight
    {
        [Required]
        [Range(1, 2)]
        public int DomesticOrInternational { get; set; }

        [Required]
        public int CountryId { get; set; }

        [Required]
        public int StateId { get; set; }

        [Required]
        public int CityId { get; set; }

        [Required]
        public int CourierId { get; set; }

        [Required]
        public int ProductId { get; set; }

        [Required]
        public TransportMode TransportMode { get; set; }

        public virtual ICollection<CostWeightList> CostWeightLists { get; set; }
    }

    // TODO: To move to new file
    public class CostWeightList
    {
        public int WeightId { get; set; }
        public float Cost { get; set; }
    }
}

Контроллер:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(
    [Bind(Include = "DomesticOrInternational,CountryId,StateId,CityId,CourierId,ProductId,TransportMode,CostWeightLists")] CostWeight costWeight)
{
    if(ModelState.IsValid)
    {
        // TODO: My Pending action
        await db.SaveChangesAsync();
        return View();
    }
    return View();            
}

POST данные:

DomesticOrInternational: 1
CountryId: 6
StateId: 4127
CityId: 48403
CourierId: 1
ProductId: 0
TransportMode: 0
CostWeightLists.WeightId: 1
CostWeightLists.Cost: 1
CostWeightLists.WeightId: 2
CostWeightLists.Cost: 2
CostWeightLists.WeightId: 3
CostWeightLists.Cost: 3
CostWeightLists.WeightId: 4
CostWeightLists.Cost: 4
CostWeightLists.WeightId: 5
CostWeightLists.Cost: 5
CostWeightLists.WeightId: 6
CostWeightLists.Cost: 6
CostWeightLists.WeightId: 7
CostWeightLists.Cost: 7
CostWeightLists.WeightId: 8
CostWeightLists.Cost: 8

Вывод отладки:

enter image description here

Вопрос :

как можноЯ беру стоимость и вес и зацикливаю это в контроллере?Есть ли возможность отправить его в виде словаря?

Можно ли создать модель для этого вида?Если да, как создать?

Пожалуйста, предоставьте любую идею / предложения.

1 Ответ

0 голосов
/ 02 декабря 2018

вам нужно изменить имя CostWeightLists, чтобы связать его как коллекцию

@using (Html.BeginForm())
{
    ... code block ...

          // BULK INSERT OF COST PER WEIGHT
            @for (var i = 0; i < ViewBag.WeightId.Length; i++)
            {
                <input type="hidden" id="WeightId" name="CostWeightLists[i].WeightId" value="@item.Value" />

                <label for="WeightId">@item.Text kg</label>
                @Html.Editor("Cost", new { htmlAttributes = new {  data_weight_id = @item.Value, name = CostWeightLists[i].Cost} })
            }

        ... code block ...
}

подробнее: ASP.NET MVC 5 Просмотр привязки коллекции моделей

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...