1
我在C#中使用EF Core 1.2的代碼,我有一個包含兩個提交按鈕的表單。第一個按鈕'upload'調用我的方法'UpLoadMyFile',它將來自我的textarea的每行與 進行比較,並返回一個字符串,告訴我它是否匹配一個模式。 後來我加我的所有文字和狀態成如何將Table中的List <Tuple>傳遞給Controller?
List <Tuple<string, string>>
,我通過一個ViewModel傳遞給我的視圖,並顯示在一個表中的每一行加上其狀態。
現在我試圖將每行保存到我的數據庫中,當我點擊第二個按鈕「保存」。但每次我嘗試保存我的行NullReferenceException發生 它告訴我我的表中的列表爲空。
我想知道如何將我的Table'MyTupleList'中的所有行和狀態傳遞給Post方法,因爲我真的不知道如何解決我的問題。
筆者認爲:
@model Models.ViewModels.CreateSaetzeModelView
<form asp-action="ProcessCreateLines" asp-controller="SoftwareService" method="post" enctype="multipart/form-data">
<div class="div-marginBottom">
<table class="table">
<tbody>
<tr>
<td>
<textarea name="ExpressionTextarea" id="ExpressionTextarea" runat="server" TextMode="MultiLine" asp-for="@Model.LoadExpressions"></textarea>
<div class="col-md-10">
<input type="submit" name="upload" value="upload" /> !--Calls 'uploadmyfile' action-->
</div>
</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<br />
<div class="div-ExpressionEingabe">
</div>
@if (Model.MyLinesList != null)
{
<div class="div-marginBottom">
<table id="MyTupleList" class="table table_align">
<thead>
<tr>
<th>
State
</th>
<th>
MyLines
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.MyLinesList)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Item2)
</td>
<td>
@Html.DisplayFor(modelItem => item.Item1)
</tr>
}
</tbody>
</table>
<input type="submit" name="save" value="save" />
</div>
}
我的代碼:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ProcessCreateLines(string upload, string save, CreateLinesModelView cmv)
{
//Button 'upload': Checking my lines
if (!string.IsNullOrEmpty(upload))
{
string expressions = Request.Form["ExpressionTextarea"].ToString();
List<Tuple<string, string>> result = new FileUploadController().CheckExpressions(expressions);
cmv.MyLinesList = result;
return View("ProcessCreateLines", cmv);
}
//Button 'save': Saving my lines into a Database
if (!string.IsNullOrEmpty(save))
{
// ****************************MyLinesList is null*******************
var list = cmv.MyLinesList;
...saving my list into database...
}
}
你的觀點並沒有存儲MyLinesList'的'內容(它只顯示標籤,而不是表單數據)。然後當你點擊保存按鈕時,表單沒有'MyLinesList'數據發送到控制器,這意味着當模型被填充時'MyLinesList'屬性將爲'null'。你的'ProcessCreateLines'方法也違反了SRP,因爲你迫使兩個完全獨立的邏輯部分以相同的方法工作(沒有明顯的理由) – Flater
@Flater如何將內容存儲在我的視圖中?我試過用 item.Item2)將其顯示爲表單數據,但我的列表仍保留爲空。 –
我不是確定如何存儲一個'List',我會假設一個簡單的'HiddenFor'不能自動地這樣做(但一定要試一下,如果有效的話,你有答案)如果我找出一個方法,我會發佈一個答案 –
Flater