I have a view that is strongly typed to a ViewModel. Is it possible to pass all of the data from a model in the view, back to a controller action? Something like this?
@Ajax.ActionLink("(Export to Excel)", "ExportCsv", "SurveyResponse", new {
ResultsViewModel = Model }, new AjaxOptions {HttpMethod = "POST"})
And then collect the data from ResultsViewModel as a parameter in another controller
public ActionResult ExportCsv(ResultsViewModel resultsviewmodel)
{
}
ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.
ActionLink is rendered as an HTML Anchor Tag (HyperLink) and hence it produces a GET request to the Controller's Action method which cannot be used to submit (post) Form in ASP.Net MVC 5 Razor. Hence in order to submit (post) Form using @Html. ActionLink, a jQuery Click event handler is assigned and when the @Html.
Call the appropriate /controller/action in your respective button click handlers. In your case for the register button handler direct it to /home/register. Have a view for your register functionality. In the register action of your home controller return the view you want to show.
No, you cannot pass entire view model like this in an action link. You could pass only the id
of this model and then retrieve the actual model using this id
from wherever you retrieved it initially:
@Ajax.ActionLink(
"(Export to Excel)",
"ExportCsv",
"SurveyResponse",
new { id = Model.Id },
new AjaxOptions { HttpMethod = "POST" }
)
As an alternative you could serialize the model as a javascript literal and then send it as a JSON data with the AJAX request:
@Html.ActionLink(
"(Export to Excel)",
"ExportCsv",
"SurveyResponse",
null,
new { @class = "exportCsv" }
)
<script type="text/javascript">
$('.exportCsv').click(function() {
var model = @Html.Raw(Json.Encode(Model));
$.ajax({
url: this.href,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(model),
success: function(result) {
}
});
return false;
});
</script>
Managed to make below works,
@Ajax.ActionLink("(Export to Excel)", "ExportCsv", "SurveyResponse",
new { Model.F1, Model.F2, Model.OtherFields }, new AjaxOptions {HttpMethod = "POST"})
Controller
[HttpPost]
public ActionResult ExportCsv(ResultsViewModel resultsviewmodel)
{
}
This is a http post, but the data in not in "form data", it's encoded in request's URL (but not a http get).
Looks like MVC automatically converts the individual fields into a single model.
URL has a length limits, large model may fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With