将不是模型一部分的额外参数传递到控制器中



我的代码下面显示了我的创建CSHTML页面,并连接到它的控制器。

它工作正常,但是现在我需要将另一个字段添加到" gamemanagement.gamemage"模型中的表单中。

此字段称为" 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);
}

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

如果您坚持不创建新的ViewModel,则可以添加名称属性:

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

并在服务器端获得价值,例如:

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

最新更新