在MVC 5中,View的两个模型之一始终为null

时间:2017-11-04 12:39:04

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

在我的MVC5应用程序中,我有两个模型订单文件,如下所示:

public class Order
{
    public int OrderID { get; set; }
    public string OrderName{ get; set; }
}

public class File
{
    public HttpPostedFileBase[] files { get; set; }  
}

我想在单个视图中编辑两个类的对象,所以我创建了父类:

public class MainContext
{
    public Order Order { get; set; }
    public File File { get; set; }
}

在视图中我有这个:

@using (Html.BeginForm("Create", "Order", FormMethod.Post, new { encType = "multipart/form-data" }))
@Html.AntiForgeryToken()

<div class="form-group">
    <label>OrderName</label>
    @Html.EditorFor(model => model.Order.OrderName, new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.Order.OrderName, "", new { @class = "text-danger" })
</div>

<div class="form-group">
    @Html.LabelFor(model => model.File.files, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.TextBoxFor(model => model.File.files, "", new { @type = "file", @multiple = "multiple", })
        @Html.ValidationMessageFor(model => model.File.files, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    <input type="submit" value="submit" class="btn btn-success btn-lg btn-block" />
</div>

控制器

public ActionResult Create()
{
   return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "OrderName")] Order order, HttpPostedFileBase[] files)
{
    if (ModelState.IsValid)
    {
        db.Order.Add(order);
        db.SaveChanges();

        if (files != null)
        {
            foreach (HttpPostedFileBase file in files)
            {
                if (file != null)
                {
                    var InputFileName = Path.GetFileName(file.FileName);
                    var ServerSavePath = Path.Combine(Server.MapPath("~/UploadedFiles/") + InputFileName);
                    file.SaveAs(ServerSavePath);
                }
            }
        }
        return RedirectToAction("Index");
    }
}

现在问题 ..在我提交表单后,我在创建操作中获得了订单值但文件始终为NULL!

我想念的是什么

提前致谢

1 个答案:

答案 0 :(得分:1)

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(MainContext model)
{
  // here fetch values from model.Order and model.File
}

而不是分别获取两个模型,在post动作中调用“MainContext”类,从中可以获得所有视图值....