简体   繁体   English

如何将 model 从视图传递到 controller?

[英]How to pass the model from view to controller?

So as a short story, I want to generate a PDF with some data I have on my view.因此,作为一个简短的故事,我想生成一个 PDF ,其中包含我认为的一些数据。 All data are stored in the model.所有数据都存储在 model 中。 So on submit button click of Generate PDF button I want to pass the model to controller.因此,在提交按钮单击Generate PDF按钮时,我想将 model 传递给 controller。

Model:

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

View.cshtml:查看.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 : 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 .我不明白为什么分析是null Is something wrong on my view?我的观点有问题吗?

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.由于您的观点 model 包含简单的类型属性,它已经在绑定上下文中,您不需要在@Url.Action()中将其指定为路由值。

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).当您提交表单时,提交的数据类型将是您的 model 类型,其中的数据取自表单(预期)。 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"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM