-1

In my MVC5 application I have two model Order and File as following:

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

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

I want edit objects of both classes in single view, so I create parent class:

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

In the view I have this:

@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>

The Controller

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");
    }
}

Now the problem .. after I submit the form I got order values in Create action BUT files is always NULL !

What I miss

Thanks in advance

Abdulsalam Elsharif
  • 4,773
  • 7
  • 32
  • 66

1 Answers1

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

Instead of fetching two models separately call "MainContext" class in post action, from that you can get all the view values....

Jilani pasha
  • 389
  • 3
  • 14