gpt4 book ai didi

c# - 如何将复杂的对象集合传递给mvc中的 Controller

转载 作者:行者123 更新时间:2023-11-30 15:31:29 25 4
gpt4 key购买 nike

我是 MVC 的新手,对于这个初学者问题我深表歉意。我有以下模型类:

public class ReturnBookHedModel
{

public int RefferenceID { get; set; }
public int BorrowedRefNo { get; set; }
public int MemberId { get; set; }
public DateTime ReturnDate { get; set; }
public bool IsNeedToPayFine { get; set; }
public DateTime CurrentDate { get; set; }

public virtual List<ReturnBookDetModel> RetunBooks { get; set; }
public virtual MemberModel member { get; set; }
}

public class ReturnBookDetModel
{

public int BookID { get; set; }
public int RefferenceID { get; set; }
public bool IsReturned { get; set; }
public virtual ReturnBookHedModel ReturnBookHed { get; set; }
public virtual BookModel book { get; set; }
}

我有以下 Controller 方法:

    public ActionResult SaveReturnBook(int refNo)
{
ReturnBookHedModel model = ReturnBookFacade.GetReturnBookBasedOnRefference(refNo);
return View(model);
}

//
// POST: /ReturnBook/Create

[HttpPost]
public ActionResult SaveReturnBook(ReturnBookHedModel model)
{
try
{
// TODO: Add insert logic here

return RedirectToAction("Index");
}
catch
{
return View();
}
}

在我的模型中我定义如下:

     <div class="control-label">
@Html.LabelFor(model => model.BorrowedRefNo)
@Html.TextBoxFor(model => model.BorrowedRefNo, new { @class = "form-control" ,@readonly = "readonly" })
@Html.ValidationMessageFor(model => model.BorrowedRefNo)

</div>
// rest of the header details are here
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.RetunBooks.FirstOrDefault().IsReturned)
</th>
<th>
@Html.DisplayNameFor(model => model.RetunBooks.FirstOrDefault().BookID)
</th>
<th>
@Html.DisplayNameFor(model => model.RetunBooks.FirstOrDefault().book.BookName)
</th>
<th></th>
</tr>

@foreach (var item in Model.RetunBooks)
{
<tr >
<td>
@Html.CheckBoxFor(modelItem => item.IsReturned)
</td>
<td>
@Html.HiddenFor(modelItem => item.BookID);
@Html.DisplayFor(modelItem => item.BookID)
</td>
<td>
@Html.DisplayFor(modelItem => item.book.BookName)
</td>
</tr>
}
</table>

这工作正常..但这些表详细信息(复杂对象)不在 Controller 的 post 方法中。当我搜索时,我发现我可以按如下方式使用此详细数据:但我不能按如下方式使用它。

  @for (var i = 0; i < Model.RetunBooks.Count; i++) 
{
<tr>
<td>
@Html.CheckBoxFor(x => x.RetunBooks.)
</td>
</tr>
}

我如何将这些信息发送给 Controller

最佳答案

为了将集合发回,您需要按以下方式为它们建立索引,以便模型绑定(bind)器能够拾取它们。

这应该可以解决问题:

 @for (var i = 0; i < Model.RetunBooks.Count; i++) 
{
...
@Html.CheckBoxFor(model => Model.RetunBooks[i].IsReturned)
...
}

复杂的对象需要按上述方式进行索引。

有关它的更多信息,请参见此处:

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

关于c# - 如何将复杂的对象集合传递给mvc中的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20599486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com