将不属于模型的额外参数传递到控制器中

时间:2019-03-08 18:51:11

标签: razor entity-framework-6 asp.net-core-mvc

我下面的代码显示了“创建cshtml”页面和与其连接的控制器。

它工作正常,但是现在我需要向不在GameManagement.Game模型中的表单添加另一个字段。

此字段称为“ CreatorUserId”,在我使用的模型中不存在。

但是我是否要获取此字段的值,然后在它不属于模型的一部分时将其传递给控制器​​?

谢谢!

Create.cshtml:

@model GameManagement.Game


<div>
    <div>
        <form asp-action="Create">
            <div>
                <label asp-for="Id"></label>
                <input asp-for="Id" />
            </div>
            <div>
                <label asp-for="Description"></label>
                <input asp-for="Description" />
            </div>
            <div>
                <label asp-for="DisplayName"></label>
                <input asp-for="DisplayName" />
            </div>
            <div>
                <label>Creator User ID</label>
                <input id="CreatorUserId" />
            <div>
                <input type="submit" value="Create" />
            </div>
        </form>
    </div>
</div>

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Description,DisplayName")] Game newGame)
{

     // code to send the form information (Id, Description, DisplayName) to a 3rd party API

     apiResult = await apiClient.createNewGame(
        newGame.Id,
        newGame.Description,
        newGame.DisplayName,
        // CreatorUserId ??  not in Game model....

     return View(apiResult);
}

1 个答案:

答案 0 :(得分:1)

正如@ johnluke.laue建议的那样,最好的解决方案是创建一个新的视图模型以包含所需的属性。

如果您坚持不创建新的视图模型,则解决方法是添加名称属性:

<input id="CreatorUserId" name="CreatorUserId" />

在服务器端获取价值,如:

public async Task<IActionResult> Create([Bind("Id,Description,DisplayName")] Game newGame, string CreatorUserId)
{
}