Asp.net mvc 将额外参数与HttpPostedFileBase对象一起传递

Asp.net mvc 将额外参数与HttpPostedFileBase对象一起传递,asp.net-mvc,model-view-controller,Asp.net Mvc,Model View Controller,在我的MVC应用程序中,我有一个带有GET和POST操作的上传视图 问题是如何将额外数据与HttpPostedFileBase对象一起传递给POST操作,例如,某个ID。您只需将其作为附加参数传递即可 HTML: <form action="" method="post" enctype="multipart/form-data"> <input type='text' id='txtId' name='id'/> <input type="file" na

在我的MVC应用程序中,我有一个带有GET和POST操作的上传视图


问题是如何将额外数据与HttpPostedFileBase对象一起传递给POST操作,例如,某个ID。

您只需将其作为附加参数传递即可

HTML:

<form action="" method="post" enctype="multipart/form-data">
  <input type='text' id='txtId' name='id'/>
  <input type="file" name="file" id="file" />

  <input type="submit" />
</form>
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, string id) {

  if (file.ContentLength > 0) {
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file.SaveAs(path);
  }

  return RedirectToAction("Index");

}

只需将其作为附加参数传递即可

HTML:

<form action="" method="post" enctype="multipart/form-data">
  <input type='text' id='txtId' name='id'/>
  <input type="file" name="file" id="file" />

  <input type="submit" />
</form>
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, string id) {

  if (file.ContentLength > 0) {
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file.SaveAs(path);
  }

  return RedirectToAction("Index");

}

谢谢Ryand,最初作为查询字符串从GET操作到达的Id参数,我是否应该将其传递到ViewData字典并在视图中作为隐藏字段呈现?您是否使用默认的controller/action/Id路由?您可以将其作为路由的id部分传递,而不是查询字符串。因此,您的get将是“public ActionResult Upload(string id)”,而[httppost]将是“public ActionResult(httppostedfilebase文件,string id)”感谢Ryand,最初作为查询字符串从GET操作到达的Id参数,我是否应该将其传递到ViewData字典并在视图中作为隐藏字段呈现?是否使用默认路由controller/action/Id?而不是查询字符串,您可以将其作为路由的Id部分传递。因此,您的GET将是“public ActionResult Upload(字符串id)”和[httppost]将是“public ActionResult(httppostedfilebase文件,字符串id)