Skip to main content
 首页 » 编程设计

c#之隐藏字段不随文件一起发布

2024年02月20日12jiqing9006

我有以下 MVC 表单和 Controller 来上传具有给定 ID 的商品图片。由于某种原因将此表单提交给 Controller 时,id 为空。我检查了呈现的 HTML,网页上呈现了正确的 ID。

形式:

@using(Html.BeginForm(new{id = ViewBag.id})){ 
 
<input type="hidden" name="id" id="id" value="@ViewBag.Id"/> 
 
<label for="file">Filename:</label> 
<input type="file" name="file" id="file" /> 
<input type="submit" /> 
} 

和 Controller :

[HttpPost] 
public ActionResult AddImage(int merchandiseId, HttpPostedFileBase image) 
<snip> 

为什么提交此表单会导致 merchandiseId 为空?

请您参考如下方法:

因为你用错了名字。变化

<input type="hidden" name="id" id="id" value="@ViewBag.Id"/> 

到

<input type="hidden" name="merchandiseId" id="id" value="@ViewBag.Id"/> 

或

public ActionResult AddImage(int merchandiseId, HttpPostedFileBase image) 

到

public ActionResult AddImage(int id, HttpPostedFileBase image)