MVC如何更新相关的导航属性

时间:2017-03-30 22:18:10

标签: c# asp.net-mvc razor many-to-many

EDIT根据@Stephen Muecke回答改编了我的问题..

我花了几个月的时间试图解决这个问题,但未能如此。

我的实体是:

public partial class Book
{
    public int bookID { get; set; }
    public string name { get; set; }
    public string chapter { get; set; }
    public virtual ICollection<Root> roots { get; set; }
}

public class Root
{
    public int rootID { get; set; }
    public string rooting { get; set; }
    public virtual ICollection<Book> Book{ get; set; }
}

BooksController中:

public class BooksController : Controller
{
    private Context db = new Context();

    // GET: Books
    public ActionResult Index()
    {
        var boo = db.books.Include(x => x.roots).ToList();
        List<RootyVM> model = new List<RootyVM>();
        return View(boo);
    }
....
....
// GET: Books/Create
    public ActionResult Create()
    {
        return View();
    }
    // POST: Books/Create
 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(IEnumerable<RootyVM> rootings, Book book)
    {
        if (ModelState.IsValid)
        {
            db.books.Add(book);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(book);
    }

我的视图模型RootyVM:

public class RootyVM
{
    public int? rootID { get; set; }

    [Required(ErrorMessage = "Please enter the name of the root!!")]
    public string rooting { get; set; }

}

和我的部分视图_Rooting.cshtml

@model project.ViewModels.RootyVM
<div class="rooting">
@using (Html.BeginCollectionItem("rooting"))
{
    @Html.HiddenFor(m => m.rootID, new { @class = "rootID" })
    @Html.LabelFor(m => m.rooting)
    @Html.TextBoxFor(m => m.rooting)

    <button type="button" class="delete">Delete</button>
}
</div>

和我的Razor视图(Create.cshtml)如下:

@model project.Models.Book

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Book</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.chapter, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.chapter, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.chapter, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @using (Html.BeginForm())
        {
            <div id="rootings">
                foreach(var rooting in Model)
                {
                @Html.Partial("_Rooting", rooting)
                }
            </div>
            <button id="add" type="button">Add</button>
            <input type="submit" value="Save" />
        }
    </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>

<script type="text/javascript">
var url = '@Url.Action("Rooting")';
var form = $('form');
var rootings = $('#rootings');
$('#add').click(function() {
    $.get(url, function(response) {
        rootings.append(response);
        // Reparse the validator for client side validation
        form.data('validator', null);
        $.validator.unobtrusive.parse(form);
    });
});

$('.delete').click(function() {
    var container = $(this).closest('.rooting');
    var id = container.find('.id').val();
    if (id) {
        // make ajax post to delete item
        $.post(yourDeleteUrl, { id: id }, function(result) {
            container.remove();
        }.fail(function (result) {
            // Oops, something went wrong (display error message?)
        }
    } else {
        // It never existed, so just remove the container
        container.remove();
    }
    });
</script>
}

HOWEVER, there is a mistake where i cannot find. Will appreciate your patience and help

原始主要要求

然而,我在创建和编辑方法上苦苦挣扎。我需要做的是:

  • 创建新的图书记录,并在同一视图中指定一个或多个根。
  • 最好使用下拉列表。
  • 如果root不存在,我想动态添加/创建它,我的意思是立即在同一个创建视图中。
  • 如果关系属性的创建视图(即Root)基于使用令牌的java(Select2),我将不胜感激。

我希望我明确表示你能帮助我。

0 个答案:

没有答案