我创建了viewmodel视图,允许我在我的视图中使用2模型(Fax& Faxdata) 但我在listboxfor中有SelectedEmployees的NULL值 我的viewmodel中有什么问题?
namespace FaxProject.ViewModel
{
public class SendFaxVm
{
public List<SelectListItem> Employees { set; get; }
public int[] SelectedEmployees { set; get; }
public Fax fax { set; get; }
}
}
这是视图(Edite视图)
@model FaxProject.ViewModel.SendFaxVm
@using (Html.BeginForm("Edit","Fax"))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Fax</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.fax.Id)
<div class="form-group">
@Html.LabelFor(model => model.fax.Courier_Num, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.fax.Courier_Num, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.fax.Courier_Num, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.fax.NumberOfPages, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.fax.NumberOfPages, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.fax.NumberOfPages, "",
<div class="form-group">
@Html.LabelFor(model => model.Employees, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.ListBoxFor(a => a.SelectedEmployees, Model.Employees)
@Html.ValidationMessageFor(a => a.SelectedEmployees)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Back" class="btn btn-default" />
</div>
</div>
</div>
}
我在列表框中得到了null异常所以如何获得编辑它的员工列表?
public ActionResult Edit (int id,SendFaxVm vm,Fax fax)
{
var faxindb = Db.Faxes.Single(f=>f.Id==id);
faxindb.Courier_Num = fax.Courier_Num;
faxindb.NumberOfPages = fax.NumberOfPages;
faxindb.CompanyName = fax.CompanyName;
faxindb.ReceivingDate = fax.ReceivingDate;
faxindb.Attachment = fax.Attachment;
faxindb.Subject = fax.Subject;
Db.SaveChanges();
foreach (var userId in vm.SelectedEmployees)
{
var faxdataindb = Db.FaxDatas.Single(f => f.FaxId == fax.Id);
faxdataindb.EmpId = userId;
//to do : Save fd
Db.SaveChanges();
}
return RedirectToAction("FaxForm","Fax");
}
这是传真控制器中的操作...
答案 0 :(得分:0)
嘿,你可以改善几件事。
public class SendFaxVm
{
public List<SelectListItem> Employees { set; get; }
public List<int> SelectedEmployees { set; get; }
public Fax fax { set; get; }
}
将数组更改为模型中的List,您也可以在此处使用IEnumerable。如果您,也请按照此示例填充列表框https://www.codeproject.com/Articles/771999/ASP-Net-MVC-How-to-create-a-ListBox