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

C# 隐藏字段不随文件一起发布,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,我有以下MVC表单和控制器,用于上载具有给定id的商品的图像。由于某种原因,当此表单提交给控制器时,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> <

我有以下MVC表单和控制器,用于上载具有给定id的商品的图像。由于某种原因,当此表单提交给控制器时,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" />
}
以及控制器:

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

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

因为您使用了错误的名称。改变

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


因为你用错了名字。改变

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

merchandiseId将为0且不为null,因为在名为merchandiseId的表单上没有输入

merchandiseId将为0且不为null,因为在名为merchandiseId的表单上没有输入

更改Html.begin,如下所示:

@using(Html.BeginForm(new{merchandiseId = ViewBag.id}))
这将解决您的问题。

更改Html.begin,如下所示:

@using(Html.BeginForm(new{merchandiseId = ViewBag.id}))
这会解决你的问题

<input type="hidden" name="merchandiseId" id="merchandiseId" value="@ViewBag.Id"/>
@using(Html.BeginForm(new{merchandiseId = ViewBag.id}))