Submitting form and pass data to controller method of type FileStreamResult

jpo picture jpo · Jan 2, 2013 · Viewed 218.3k times · Source

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?

Answer

Forty-Two picture Forty-Two · Jan 2, 2013

When in doubt, follow MVC conventions.

Create a viewModel if you haven't already that contains a property for JobID

public class Model
{
     public string JobId {get; set;}
     public IEnumerable<MyCurrentModel> myCurrentModel { get; set; }
     //...any other properties you may need
}

Strongly type your view

@model Fully.Qualified.Path.To.Model

Add a hidden field for JobId to the form

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post))
{   
    //...    
    @Html.HiddenFor(m => m.JobId)
}

And accept the model as the parameter in your controller action:

[HttpPost]
public FileStreamResult myMethod(Model model)
{
    sting str = model.JobId;
}