開發者在 Edit 頁面點擊保存後跳轉 Index 時拋出異常:無法將類型為“System.Int32”的對象強制轉換為類型“System.Array”。錯誤堆疊指向模型綁定階段,經排查是模型屬性類型與視圖表單字段不匹配導致。
模型中這個屬性:
[DisplayName("職稱代碼")]
[MaxLength(3)]
public int TitleID { get; set; } // 整數類型
但視圖 Edit.cshtml 中對應的表單字段可能渲染為:
<select name="TitleID" multiple>...</select>
// 或
<input name="TitleID" value="1,2,3" /> // 逗號分隔字符串
提交時瀏覽器發送 TitleID=1,2,3(字符串),模型綁定器嘗試解析為 int[] 或 List<int>,但目標屬性是 int,類型不匹配拋出異常。
確保單選控件,移除 multiple 屬性:
@Html.DropDownListFor(m => m.TitleID, Model.TitleList, "請選擇", new { @class = "form-control" })
// 或
<select name="TitleID" class="form-control">
@foreach (var item in Model.TitleList) {
<option value="@item.Value">@item.Text</option>
}
</select>
若業務確需多選,改模型屬性類型:
public int[] TitleIDs { get; set; } // 或 List<int>
控制器動作參數自動綁定數組。
public class CommaSeparatedIntBinder : IModelBinder {
public object BindModel(ControllerContext cc, ModelBindingContext bc) {
var value = bc.ValueProvider.GetValue(bc.ModelName);
if (value == null) return 0;
var parts = value.AttemptedValue.Split(',');
return int.TryParse(parts[0], out int r) ? r : 0; // 取第一個
}
}
// 註冊:ModelBinders.Binders.Add(typeof(int), new CommaSeparatedIntBinder());
原代碼混用 Response.Write 輸出腳本,不符合 MVC 模式:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(RetireeModel model) {
if (!ModelState.IsValid) return View(model); // 返回原視圖顯示驗證錯誤
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
TempData["Success"] = "保存成功"; // 用 TempData 傳遞提示
return RedirectToAction("Index");
}
Index 視圖中讀取 TempData["Success"] 顯示彈窗,避免在 Controller 輸出 HTML/JS。
int/string,多選用 int[]/List<int>@Html.EditorFor/DropDownListFor 強類型助手,編譯期即可發現類型不匹配