我控制器的創建方法結合到一個TestCase對象:ASP.NET核心添加參數控制器的創建方法
public async Task<IActionResult> Create([Bind("Name, Description")] TestCase testCase)
並做模型綁定需要一個視圖模型中,它是像這樣指定的視圖:
public class CreateTestCaseViewModel
{
public string ProjectName { get; set; }
public TestCase TestCase { get; set; }
}
我的觀點的代碼(這僅僅是一個形式,你輸入名稱和說明,並提交)是:
@model CreateTestCaseViewModel
@{
ViewData["Title"] = "Create";
}
<h2>Create Test Case</h2>
<form asp-action="Create">
<div class="form-horizontal">
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="TestCase.Name" class="col-md-2 control-label">
</label>
<div class="col-md-10">
<input asp-for="TestCase.Name" class="form-control" />
<span asp-validation-for="TestCase.Name" class="text-danger"></span>
</div>
</div>
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="TestCase.Description" class="col-md-2 control-label"></label>
<div class="col-md-8">
@*<input asp-for="Description" class="form-control" />*@
<input asp-for="TestCase.Description" textarea class="form-control" id="Description" rows="5"/>
<span asp-validation-for="TestCase.Description" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default"/>
</div>
</div>
</div>
<div>
<a asp-action="Details">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
我的目標是我的方法,以便能夠把項目名作爲參數,以及:
public async Task<IActionResult> Create([Bind("Name, Description")] TestCase testCase, string projectName)
我怎樣才能從視圖中添加呢?
我不想爲項目名添加新的輸入,它已經在那裏,我只是想不使用會話存儲它。我也試過了,無法綁定到視圖模型的屬性......我必須重命名它們嗎? –
然後,使用類似於其他答案所暗示的隱藏字段。目前爲止的答案都是很好的解決方案 – ssmith
如果遇到問題,請從創建操作中刪除'[Bind(「」)],直到您將其排除。您也可以嘗試使用'@ Html.EditorFor(Model.TestCase.Name)'而不是'asp-for'標籤助手來確保您的目標是正確的屬性名稱。 –