向控制器方法返回项目列表
本文关键字:项目 列表 返回 方法 控制器 | 更新日期: 2023-09-27 17:50:17
我的数据库中有这些表,press, Paper和presspapervelocity:
Presses
----------------
PressID (PK)
Name
Paper
----------------
PaperID (PK)
Name
PressPaperSpeeds
----------------
PressPaperSpeedID (PK)
PressID (FK)
PaperID (FK)
Speed
当我添加一个Press时,我希望有一个表来添加presspaperspeed。在一列中,它包含所有的论文,在另一列中,一个输入速度的文本框。下面是我在视图页面上创建Press的内容:
<table>
<% foreach(Paper paper in Model.Papers) { %>
<tr>
<td><%: paper.Name %></td>
<td><input type="text" /></td>
</tr>
<% } %>
</table>
我的视图模型包含Papers
,它只是数据库中所有论文的集合。
[HttpPost]
public ActionResult Create(PressesViewModel viewModel)
{
Press press = new Press();
TryUpdateModel(press);
if (ModelState.IsValid)
{
//somehow get all values for Press Paper Speeds and save them here
DBRepository.SavePress(press);
return RedirectToAction("Details", new { id = press.PressID });
}
return View(viewModel);
}
我怎么能得到PaperID和速度值从文本框的速度表,并返回到我的控制器?
那么我将创建我的视图模型,如
public class PressViewModel
{
public int PressID{get;set;}
public string Name{get;set;}
public IEnumerable<VMPressPaperSpeed> PressPaperSpeeds{get;set;}
}
public class VMPressPaperSpeed{
public int PressPaperSpeedID{get;set;}
public int PressID{get;set;}
public int PaperID{get;set;}
public string PaperName{get;set;}// for view purpose
public int Speed{get;set;}//change data type for speed accordingly
}
我的控制器看起来像
[HttpGet]
public ActionResult Create()
{
var model = new PressViewModel();
model.PressPaperSpeeds = _SomeRepository.PopulatePaperDataLeavingIDsUntouched();
// after this line i will have all paper information inside my viewmodel's property that will be passed to view and user will enter corresponding speeds for current press
}
我的视图看起来像
<%:Html.LabelFor(x=>x.Name)>
<%:Html.TextBoxFor(x=>x.Name)>
<%:Html.HiddenFor(x=>x.ID)%>
<%for(int i=0;i<Model.PressPaperSpeeds.Count;i++){%>
<%:Html.PaperName%>
<%:Html.Hidden("Model.PressPaperSpeeds["+i+"].PressPaperID" Model.PressPaperSpeeds[i].PressPaperSpeedID)%>
<%:Html.Hidden("Model.PressPaperSpeeds["+i+"].PressID" Model.PressPaperSpeeds[i].PressID)%>
<%:Html.Hidden("Model.PressPaperSpeeds["+i+"].PaperID" Model.PressPaperSpeeds[i].PaperID)%>
<%:Html.TextBox("Model.PressPaperSpeeds["+i+"].Speed" Model.PressPaperSpeeds[i].Speed)%>
<%:Html.Hidden("Model.PressPaperSpeeds["+i+"].PaperName" Model.PressPaperSpeeds[i].PaperName)%>
把所有的东西都填好,然后按提交按钮。去post action方法,设置一个断点,看到东西会在你的viewModel和tryUpdate模型中填充,也应该工作,但你必须在你的viewModel中命名属性,就像它们在Model中一样。不要错过EntitySet属性名