I have an mvc form (made from a model) which when submitted, I want to get a parameter I have the code to set the form and get the parameter
using (@Html.BeginForm("myMethod", "Home", FormMethod.Get, new { id = @item.JobId })){
}
and inside my home controller I have
[HttpPost]
public FileStreamResult myMethod(string id)
{
sting str = id;
}
However, I always get the error
The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
When I omit the [HttpPost]
, the code executes file but the variables str
and id
are null.
How can I fix this please?
EDIT
Can this be caused because myMethod in the controller is not an ActionResult? I realized that when I have a method of type Actionresult where the method is bound to a view, everything works well. But the type FileStreamresult cannot be bound to a View. How can I pass data to such methods?
here the problem is model binding if you specify a class then the model binding can understand it during the post if it an integer or string then you have to specify the [FromBody] to bind it properly.
make the following changes in FormMethod
}
and inside your home controller for binding the string you should specify [FromBody]
FromBody is available in System.Web.Http. make sure you have the reference to that class and added it in the cs file.
When in doubt, follow MVC conventions.
Create a viewModel if you haven't already that contains a property for JobID
Strongly type your view
Add a hidden field for JobId to the form
And accept the model as the parameter in your controller action:
This is because you have specified the form method as GET
Change code in the view to this:
You seem to be specifying the form to use a HTTP 'GET' request using
FormMethod.Get
. This will not work unless you tell it to do a post as that is what you seem to want the ActionResult to do. This will probably work by changingFormMethod.Get
toFormMethod.Post
.As well as this you may also want to think about how Get and Post requests work and how these interact with the Model.