我按照这个例子来制作n到n的关系
它工作正常但是对于与数据库的有效负载的n到n的关系我弄清楚我可以做[HttpGet]并显示我想要显示的视图但现在我想知道我怎么能得到文本框在我看来,我可以在我的控制器中找到复选框(请参阅下面的操作),这是我的观点所以我的问题是如何获得文本框呢?在我的控制器中为每个复选框?
@using (Html.BeginForm("AgregarEmpresas", "Empleado"))
{
<fieldset>
<div class="editor-field">
<table>
<tr>
@{
int cnt = 0;
List<ITCOrganigrama.ViewModel.AsignarEmpresa> empresas = ViewBag.Empresas;
foreach (var empresa in empresas)
{
if (cnt++ % 5 == 0) {
@: </tr> <tr>
}
@: <td>
<input type="checkbox"
name="selectedEmpresa"
value="@empresa.EmpresaId"
@(Html.Raw(empresa.Assigned ? "checked=\"checked\"" : "")) />
@empresa.Nombre
<div>
@Html.LabelFor(model => empresa.cargo)
@Html.TextBoxFor(model => empresa.cargo, new { style = "width: 150px;" })
@Html.ValidationMessageFor(model => empresa.cargo)
</div>
@:</td>
}
@: </tr>
}
</table>
</div>
<p>
<input type="submit" value="Agregar" />
</p>
</fieldset>
}
我获得chekbox的行动
[HttpPost]
public ActionResult AgregarEmpresas(int? id, FormCollection formCollection, string[] selectedEmpresa)
{
}
我的最终观点: http://s3.subirimagenes.com:81/otros/previo/thump_7406511add1.jpg http://www.subirimagenes.com/otros-add1-7406511.html
编辑:
ViewModel Class
public class AsignarEmpresa
{
public int EmpresaId { get; set; }
public string Nombre { get; set; }
public string cargo { get; set; }
public bool Assigned { get; set; }
}
答案 0 :(得分:0)
查看您的帖子操作及其参数。这些名称非常重要。
您的复选框
<input type="checkbox"
name="selectedEmpresa"
value="@empresa.EmpresaId"
工作正常,请查看输入名称“ selectedEmpresa ”,其名称与 Controller Action 定义中的名称相同。模型绑定器在发布的数据中查找此名称,如果找到它,则从中创建对象。在您的情况下,他将尝试将数据解析为 string [] 对象。
所以......首先,你必须将动作定义改为类似的东西。
[HttpPost]
public ActionResult AgregarEmpresas(int? id, FormCollection formCollection, string[] selectedEmpresa,string [] empresaTextBox)
{
}
然后你必须改变生成的html。
@Html.TextBoxFor(model => empresa.cargo, new { style = "width: 150px;", name="empresaTextBox" })
根据这些更改,您应该在操作中获得一些数据。但是你会得到一些奇怪的东西,因为你有多个复选框和文本框,以便告诉模型活页夹你必须准备多个元素来准备包含的输入的特殊名称索引号。
看看这个例子
<input name="childs[0]"></input>
<input name="childs[1]"></input>
在这种情况下, Model Binder 将创建包含其中两个的对象数组。
所以最后你的代码必须看起来像这样。
@using (Html.BeginForm("AgregarEmpresas", "Empleado"))
{
<fieldset>
<div class="editor-field">
<table>
<tr>
@{
int cnt = 0;
int i=0;
List<ITCOrganigrama.ViewModel.AsignarEmpresa> empresas = ViewBag.Empresas;
foreach (var empresa in empresas)
{
if (cnt++ % 5 == 0) {
@: </tr> <tr>
}
@: <td>
<input type="checkbox"
name="selectedEmpresa[@i]"
value="@empresa.EmpresaId"
@(Html.Raw(empresa.Assigned ? "checked=\"checked\"" : "")) />
@empresa.Nombre
<div>
@Html.LabelFor(model => empresa.cargo)
@Html.TextBoxFor(model => empresa.cargo, new { style = "width: 150px;" ,name=String.Format("empresaTextBox\[{0}\]",i) })
@Html.ValidationMessageFor(model => empresa.cargo)
</div>
@:</td>
i++;
}
@: </tr>
}
</table>
</div>
<p>
<input type="submit" value="Agregar" />
</p>
</fieldset>
}
如果你能让它发挥作用。然后我会尝试使用一个布尔和一个字符串值创建一个类。通过这种更改,您可以对类数组进行操作,而不是使用两个带字符串的数组。