加入两个桌子以展示汽车的品牌



我正在尝试加入两个模型 Brand of carModel of car

using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace TriglavOsiguranje.Models
{
    public class ModeliVozila
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [MaxLength(20)]
        public string Ime { get; set; }

        public virtual MarkeVozila MarkeVozila { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace TriglavOsiguranje.Models
{
    public class MarkeVozila
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [MaxLength(30)]
        public string Ime { get; set; }
        public virtual ICollection<ModeliVozila> ModeliVozila { get; set; }
    }
}

和我的create.cshtml我想显示下拉列表以选择哪种汽车连接到品牌就像沃尔沃 ->赛车品牌S60->汽车型号到目前为止,我在控制器中所做的工作,我正在尝试使用

传递ID
ViewBag.MarkeVozilaId = new SelectList(_db.MarkeVozila, "Id", "Name", modeliVozila.MarkeVozila);

并显示在我的创建视图中,但是我发现该对象未设置为对象的实例到目前为止,这是我的控制器

    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.EntityFrameworkCore;
    using TriglavOsiguranje.Data;
    using TriglavOsiguranje.Models;
    namespace TriglavOsiguranje.Areas.Admin.Controllers
    {
        [Area("Admin")]
        public class ModeliVozilaController : Controller
        {
            private readonly ApplicationDbContext _db;
            public ModeliVozilaController(ApplicationDbContext db)
            {
                _db = db;
            }
            public IActionResult Index()
            {
                return View(_db.Modeli.Include(m => m.MarkeVozila).ToList());
            }
    //GET Create Action Metod
    public IActionResult Create()
    {
        ViewBag.MarkeVozilaId = new SelectList(_db.MarkeVozila, "Id", "Name");
        return View();
    }

//POST Create Action Metod
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(ModeliVozila modeli)
    {
        if (ModelState.IsValid)
        {
            _db.Add(modeli);
            await _db.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        ViewBag.MarkeVozilaId = new SelectList(_db.MarkeVozila, "Id", "Name", modeli.MarkeVozila);
        return View(modeli);
    }

    //GET Edit Action Metod
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }
        var modeliVozila = await _db.Modeli.FindAsync(id);
        if (modeliVozila == null)
        {
            return NotFound();
        }
        ViewBag.MarkeVozilaId = new SelectList(_db.MarkeVozila, "Id", "Name");
        return View(modeliVozila);
    }

  //POST Edit Action Metod
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, ModeliVozila modeliVozila)
    {
        if (id != modeliVozila.Id)
        {
            return NotFound();
        }
        if (ModelState.IsValid)
        {
            _db.Update(modeliVozila);
            await _db.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        ViewBag.MarkeVozilaId = new SelectList(_db.MarkeVozila, "Id", "Name", modeliVozila.MarkeVozila);
        return View(modeliVozila);
    }

任何人都知道如何以简短的方式做到这一点,我不希望什么都不那么复杂基本上仅显示汽车的品牌

我创建了一个小示例项目,您可以在其中看到如何完成。我无法在您的代码中看到任何错误,但也许您会看到一个区别:

模型(Marka(:

namespace WebApplication22.Models
{
    public class Marka
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

模型(模型(:

namespace WebApplication22.Models
{
    public class Model
    {
        public int Id { get; set; }
        public int MarkaId { get; set; }
        [ForeignKey(nameof(MarkaId))]
        public virtual Marka Marka { get; set; }
    }
}

视图(创建(:

@model WebApplication22.Models.Model
@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <h4>Model</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.MarkaId, "MarkaId", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("MarkaId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.MarkaId, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

控制器(帖子创建(:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,MarkaId")] Model model)
{
    if (ModelState.IsValid)
    {
        db.Models.Add(model);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    ViewBag.MarkaId = new SelectList(db.Markas, "Id", "Name", model.MarkaId);
    return View(model);
}

我希望对您有帮助!

最新更新