javascript - asp.net mvc 如何将 View 模型和输入文本传递给 Controller ​​?

标签 javascript c# html razor

我正在尝试下载一个带有 html.actionlink(text, action, controller, reoute values, htmlattributes) 的文件

我正在尝试通过 view model以及来自 <input type="text" 的文本到 Controller 。但我在将输入文本传递到 MVC Controller 时遇到问题。我正在使用 actionlink因为我似乎无法使用 post 下载文件

如何将模型值和文本输入传递到 Controller ? 这是 HTML

<body>
    <div class="col-md-12 form-group centered">
        <div class="col-md-4"></div>
            <div class="col-md-4">
                <label for="quoted">Quoted:</label>
                <input type="text" class="form-control" style="width:300px" id="quoted">
            </div>
        <div class="col-md-4"></div>

        </div>
    <div class="col-md-12 text-center">
        @Html.ActionLink("Download", "GeneratePoExportDocument", "HealthCareExport", new {model = Model, quoted = "text box input goes here" }, new { @class = "btn btn-default", id="download-btn" })
    </div>

Are there other methods to download a file where I can pass in all the values?
</body>

这是 Controller

public FileResult GeneratePoExportDocument(MyModel model, string quoted)
{
  //my model has all of the values
  //quoted is null I don't know how to pass that in
}

最佳答案

您不能也不应该像查询字符串中那样传递整个模型。呈现的 HTML 的一部分中的文本框,用户可以在其中输入任何值。因此,如果您想发送该数据,则必须使用 javascript 劫持链接的 click 事件,读取输入元素值并将其附加到查询字符串,然后通过设置 导航到该 url >window.location.href 值。

另一个(更可靠的恕我直言)选项是进行表单提交。如果您想发送 View 模型的某些属性,您可以将它们作为隐藏输入包含在表单中

<form action="@Url.Action("GeneratePoExportDocument","HealthCareExport")" method="post">

    @Html.HiddenFor(a => a.Id)
    @Html.HiddenFor(a => a.CartId)

    <label for="quoted">Quoted:</label>
    <input type="text" class="form-control" style="width:300px" name="quoted">
    <button type="submit">Download</button>
</form>

仅发送您在操作方法中绝对需要的属性。如果您只需要 Id,则仅发送该 ID。如果需要,也许您可​​以在该操作方法中根据 Id 重建整个模型。

关于javascript - asp.net mvc 如何将 View 模型和输入文本传递给 Controller ​​?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50991645/

相关文章:

c# - 外部窗口上的图像叠加

c# - Python.NET : "Cannot instantiate enumeration"

html - 为什么此文本输入的轮廓在 Chrome 中与 Firefox 中显示不同?

html - Bootstrap 3 在堆叠导航中对齐图像和链接

javascript - vite + vue3 + TS项目中,AWS Amplify Failed to resolve components

php - 如何使用 PHP 从数据库中获取已从数据库返回的数据?

c# - LINQ To Entities Include + Where 方法

javascript - Moment Js问题: isoWeekYear & isoWeek method behavior

javascript - HTML 属性事件处理程序中标识符和元素属性的范围

javascript - 我如何从附属类(class)返回165