将项目列表返回到控制器方法

时间:2011-04-14 15:48:15

标签: c# asp.net asp.net-mvc

我的数据库中有这些表,Presses,Paper和PressPaperSpeeds:

Presses
----------------
PressID (PK)
Name

Paper
----------------
PaperID (PK)
Name

PressPaperSpeeds
----------------
PressPaperSpeedID (PK)
PressID (FK)
PaperID (FK)
Speed

当我添加印刷机时,我想要一张表来添加PressPaperSpeeds。在一列中,它包含所有Papers,在另一列中,包含一个用于输入Speed的文本框。以下是我在视图页面上创建印刷机的内容:

<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 速度值,并将其返回给我的控制器?

1 个答案:

答案 0 :(得分:0)

好的,然后我将创建我的视图模型

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 post方法放置一个断点并查看将在viewModel中填充的东西和tryUpdate Model也应该也可以工作,但是你必须在viewmodel中为它们在模型中的命名方式命名。不要错过EntitySet属性名称。