Home > Software engineering >  How to pass the model from view to controller?
How to pass the model from view to controller?

Time:09-23

So as a short story, I want to generate a PDF with some data I have on my view. All data are stored in the model, so on submit button click of Generate pdf button, I want to pass the model to controller.

Model

public class Analytics
{
    public int Total { get; set; }
    public int y { get; set; }
    public int x { get; set; }
}

View.cshtml:

@model Analytics <!--this one contains all my data I need-->

<!--Display data on page->>
<p> @model.Total </p>
<p> @model.y </p>
<p> @model.x </p>

<form action="@Url.MyAction("GeneratePDF", "Analytics", @Model)" method="post">
       <button type="submit">Generate PDF</button>
</form>

AnalyticsController.cs:

[HttpPost]
public IActionResult GeneratePDF(Analytics analytics)
{
    // here is the problem, analytics is null..

    return View();
}

I do not get why the analytics is null, is something wrong on my view?

CodePudding user response:

There are a few typo in the view code above. Try to fix your code to:

@model Analytics

model Analytics <!--this one contains all my data I need-->
<!--Display data on page -->


<p> @Model.Total </p>
<p> @Model.y </p>
<p> @Model.x </p>

<form action="@Url.Action("GeneratePDF", "Analytics")" method="post">
    <button type="submit">Generate PDF</button>
</form>

Because of your view model contains simple type properties it's already in the binding context and you don't need it to specify in the @Url.Action() as route value.

CodePudding user response:

As you are submitting the form, the submitted data type will be your model type and the data inside of it is taking from the form (expecting). So you have to create some hidden input on the form, something like:

<input type="hidden" asp-for="Total"/>
<input type="hidden" asp-for="x"/>
<input type="hidden" asp-for="y"/>
  • Related