Ошибка при попытке добавления записи в бд используя DropDownListFor C# MVC

274
21 декабря 2017, 23:03

При попытке добавление новой записи в бд выскакивает ошибка

Нет элемента ViewData типа "IEnumerable", который имеет ключ "Agent"

Модель:

 public partial class Contract
 {
    public int id { get; set; }
    public string series { get; set; }
    public Nullable<int> number { get; set; }
    public int insurant { get; set; }
    public int agent { get; set; }
    public int tax { get; set; }
    public System.DateTime date { get; set; }
    public int coef { get; set; }
    public Nullable<decimal> cost { get; set; }
    public int status { get; set; }
    public virtual Agent Agent1 { get; set; }
    public virtual Coef Coef1 { get; set; }
    public virtual Insurant Insurant1 { get; set; }
    public virtual Status Status1 { get; set; }
    public virtual Tax Tax1 { get; set; }
}

Модель 2:

public partial class Agent
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Agent()
    {
        this.Contract = new HashSet<Contract>();
    }
    public int id { get; set; }
    public string fio { get; set; }
    public string code { get; set; }
    public string account { get; set; }
    public virtual AspNetUsers AspNetUsers { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Contract> Contract { get; set; }
}

ДАО класс:

public class AgentDAO
{
    private AgencyEntities dbentities = new AgencyEntities();
    public IEnumerable<Agent> GetAllAgent()
    {
        return dbentities.Agent.Select(n => n);
    }
}

Контроллер:

    [HttpGet]
    [Authorize(Roles = "Admin, Agent, Insurant")]
    public ActionResult CreateContract()
    {
        SelectList agent = new SelectList(agentDAO.GetAllAgent(), "id", "fio");
        ViewBag.Agent = agent;
        SelectList tax = new SelectList(taxDAO.GetAllTax(), "id", "name");
        ViewBag.Tax = tax;
        SelectList coef = new SelectList(coefDAO.GetAllCoef(), "id", "value");
        ViewBag.Coef = coef;
        SelectList status = new SelectList(statusDAO.GetAllStatus(), "id", "title");
        ViewBag.Status = status;
        if (User.IsInRole("Insurant"))
        {
            string id = User.Identity.GetUserId();
            Insurant insurant = insurantDAO.GetAcc(id);
            Contract contract = new Contract();
            contract.insurant = insurant.id;
            return View("CreateContract", contract);
        }
        return View("CreateContract");
    }
    [HttpPost]
    [Authorize(Roles = "Admin, Agent, Insurant")]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult CreateContract([Bind(Exclude = "id")] Contract contract)
    {
        contract.date = DateTime.Now;
        if (contractDAO.AddContract(contract))
        {
            return RedirectToAction("Index");
        }
        else
        {
            return View("CreateContract");
        }
    }

Представление:

@model WebApplication1.Models.Agency.Contract
@{
    ViewBag.Title = "CreateContract";
}
<h2>Создать договор</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
    <h4>Contract</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @if (User.IsInRole("Agent") || User.IsInRole("Admin"))
    {
        <div class="form-group">
            @Html.LabelFor(model => model.series, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.series, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.series, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.number, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.number, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.number, "", new { @class = "text-danger" })
            </div>
        </div>
    }
    <div class="form-group">
        @Html.LabelFor(model => model.insurant, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.insurant, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.insurant, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.agent, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.agent, ViewBag.Agent as SelectList)
            @Html.ValidationMessageFor(model => model.agent, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.tax, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.tax, ViewBag.Tax as SelectList)
            @Html.ValidationMessageFor(model => model.tax, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.coef, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.coef, ViewBag.Coef as SelectList)
            @Html.ValidationMessageFor(model => model.coef, "", new { @class = "text-danger" })
        </div>
    </div>
    @if (User.IsInRole("Agent") || User.IsInRole("Admin"))
    {
        <div class="form-group">
            @Html.LabelFor(model => model.cost, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.cost, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.cost, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.status, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.status, ViewBag.Status as SelectList)
                @Html.ValidationMessageFor(model => model.status, "", new { @class = "text-danger" })
            </div>
        </div>
    }
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Создать" class="btn btn-default" />
            <input type="button" class="btn btn-default" value="Отмена" onclick="location.href='@Url.Action("Index", "Home")'" />
        </div>
    </div>
</div>
}
Answer 1

Вы вызываете View("CreateContract"); в POST экшн-методе CreateContract, не подготовив окружение, в котором этот вью будет выполнятся. Сравните, сколько всего Вы делаете с ViewBag-ом в GET варианте этого метода.

READ ALSO
LINQ запрос к БД

LINQ запрос к БД

Делаю запрос к БД, сначала беру данные из таблицы Technologies, далее идет поиск, сортировка + разбиваю на страницыПолучается очень много похожего...

216
Вызвать Console.Write

Вызвать Console.Write

ConsoleWrite указан в новом потоке,но вызвать нужно его в основном - как мне основной поток получить?

253
Проект перестал компилироваться на Ios в Xamarin Live Player

Проект перестал компилироваться на Ios в Xamarin Live Player

Начал только разбираться в Visual Studio 2017, в частности работе с Xamarin FormsУстановил на телефон Xamarin Live Player, но не могу развернуть даже пустой проект...

178
Нужна помощь в upload file C# application form

Нужна помощь в upload file C# application form

Всем добрый деньПишу приложение для ПК

193