0

I have this controller

public class DownloadController : Controller
{
    [HttpPost]
    public FileContentResult GetFile(MyModel model)
    {
        // Action code
    }
}

And this model

public class MyModel
{
    public string Test { get; set; }
}

Passing model from the View to the controller works fine like this

@using (Html.BeginForm("GetFile", "Download", FormMethod.Post))
{
    @Html.HiddenFor(m => m.Test)
    <button type="submit" name="submit" class="submit">Download</button>
}

The model is correctly passed to the controller and I can do what I need to do with it.

Now, what I'm trying to achieve is to make this GetFile() controller action to be generic, so I can pass it any model, without strongly typing the model class in method signature, like I did in the example above.

I know I can achieve this by overriding GetFile() method once for each model that I have, but I'm wondering is there a better way to do this, to stay DRY as much as possible?

Thank you.

1 Answer 1

1

I'd suggest using a base class:

public class BaseGetFileModel {}

which various models will derive from.

[HttpPost]
public FileContentResult GetFile(BaseGetFileModel model)

EDIT:

OK, if you want a generic way of doing this, then you could do this:

[HttpPost]
public FileContentResult GetFile()
{
    var someValue = Request["SomeValue"];
}

You don't accept any model parameter, you simply pick up POST'd values from the request. Or you could iterate through the request values collection, if you want to avoid hard-coding key names.

Sign up to request clarification or add additional context in comments.

1 Comment

In this case, if I pass BaseGetFileModel to my method, only those members of BaseGetFileModel are visible, while any of the other members added in deriving classes are not visible, so this solution does not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.