我有一个mvc表单(由模型制作),在提交时,我想获得一个参数 我有代码来设置表单并获取参数
using (@Html.BeginForm("myMethod", "Home", FormMethod.Get, new { id = @item.JobId })){
}
在我的家庭控制器里面我有
[HttpPost]
public FileStreamResult myMethod(string id)
{
sting str = id;
}
但是,我总是收到错误
您正在寻找的资源(或其中一个依赖项)可以 已删除,更改名称,或暂时 不可用。请查看以下网址并确保其中包含该网址 拼写正确。
当我省略[HttpPost]
时,代码执行文件但变量str
和id
为空。
我该如何解决这个问题呢?
修改
这可能是因为控制器中的myMethod不是ActionResult吗?我意识到当我有一个类型为Actionresult的方法时,该方法绑定到一个视图,一切都运行良好。但FileStreamresult类型无法绑定到View。如何将数据传递给此类方法?
答案 0 :(得分:49)
如有疑问,请遵循MVC惯例。
如果尚未包含JobID
的属性,请创建一个viewModelpublic class Model
{
public string JobId {get; set;}
public IEnumerable<MyCurrentModel> myCurrentModel { get; set; }
//...any other properties you may need
}
强烈输入你的观点
@model Fully.Qualified.Path.To.Model
为表单
添加JobId的隐藏字段using (@Html.BeginForm("myMethod", "Home", FormMethod.Post))
{
//...
@Html.HiddenFor(m => m.JobId)
}
并接受模型作为控制器操作中的参数:
[HttpPost]
public FileStreamResult myMethod(Model model)
{
sting str = model.JobId;
}
答案 1 :(得分:13)
这是因为您已将表单方法指定为 GET
将视图中的代码更改为:
using (@Html.BeginForm("myMethod", "Home", FormMethod.Post, new { id = @item.JobId })){
}
答案 2 :(得分:3)
您似乎正在使用FormMethod.Get
指定使用HTTP“GET”请求的表单。除非你告诉它做一个帖子,否则这将无效,因为这似乎是你希望ActionResult做的事情。这可能会将FormMethod.Get
更改为FormMethod.Post
。
除此之外,您可能还想考虑Get和Post请求的工作方式以及这些请求与模型的交互方式。
答案 3 :(得分:3)
这里的问题是模型绑定如果你指定一个类,那么模型绑定可以在帖子中理解它,如果它是一个整数或字符串,那么你必须指定[FromBody]来正确绑定它。
在FormMethod中进行以下更改
using (@Html.BeginForm("myMethod", "Home", FormMethod.Post, new { id = @item.JobId })){
}
并在你的家庭控制器内绑定你应该指定的字符串[FromBody]
using System.Web.Http;
[HttpPost]
public FileStreamResult myMethod([FromBody]string id)
{
// Set a local variable with the incoming data
string str = id;
}
FromBody可在System.Web.Http中找到。确保你有对该类的引用并将其添加到cs文件中。