这是我在AlertSelect.cshtml中的表单:
@model edxl_cap_v1_2.Models.ContentViewModels.AlertViewModel
@{
ViewData["Title"] = "AlertSelect";
Layout = "~/Views/Shared/_CapCategoryLayout.cshtml";
}
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
@{
<h4>@Model.Alerts.Count Alerts</h4>
<form>
<select asp-for="SelectedAlertIndex" asp-items="@Model.Alert_Identifiers">
<option>Select one</option>
</select>
<asp-controller ="Alerts" asp-action="LoadAlert" method="post">
<br />
<input type="submit" name="LoadAlert" value="LoadAlert" />
</form>
}
这是我的LoadAlert()控制器动作:
[HttpPost]
public IActionResult LoadAlert(Alert obj, string LoadAlert)
{
if (!string.IsNullOrEmpty(LoadAlert))
{
ViewBag.Message = "Alert loaded successfully";
}
return View("/Views/Alerts/Index", obj);
}
AlertSelect.cshtml显示标准标题和左列以及下拉列表,并且在选择并提交后,页面将重置,而不是显示/Views/Alerts/Index.cshtml并正确填写了数据。但是,该网址会反映所选的项目:http://localhost:61453/alerts/AlertSelect?SelectedAlertIndex=2&LoadAlert=LoadAlert。
我很亲密,但显然缺少任何东西,非常欢迎您的帮助。我还想在index.cshtml页面上显示所选项目,以向用户增强他们正在处理的警报消息,但是Select Tag Helper的viewmodel(带有两个属性)与model(带有16个属性)。
按照下面的注释和答案对表单进行更改,而不是返回LoadAlert()中指定的视图,我没有模型匹配:“ InvalidOperationException:
The model item passed into the ViewDataDictionary is of type
'edxl_cap_v1_2.Models.Alert', but this ViewDataDictionary instance requires
a model item of type 'System.Collections.Generic.IEnumerable`1[edxl_cap_v1_2.Models.Alert]'.
AlertSelect.cshtml指定:
@model edxl_cap_v1_2.Models.ContentViewModels.AlertViewModel
Alert.cs指定:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace edxl_cap_v1_2.Models
{
public class Alert
{
[Key]
public int AlertIndex { get; set; }
[MaxLength(150)]
public string Alert_Identifier { get; set; }
public string Sender { get; set; }
public DateTime Sent { get; set; }
...
/Views/Alerts/Index.cshtml指定:
@model IEnumerable<edxl_cap_v1_2.Models.Alert>
@using edxl_cap_v1_2.Models
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_CapCategoryLayout.cshtml";
}
和_CapCategoryLayout指定:
@model edxl_cap_v1_2.Models.ContentViewModels.AlertViewModel
<!DOCTYPE html>
我仍然看不到
The model item passed into the ViewDataDictionary is of type
'edxl_cap_v1_2.Models.Alert'
除了作为Alert.cs的命名空间之外,都可以发挥作用。为了避免这些类型的不匹配,我需要更改什么?
答案 0 :(得分:0)
在Core MVC中定义表单标签助手的正确方法应该是这样的(请参见文档here):
<form asp-controller="Alerts" asp-action="LoadAlert" method="post">
<select asp-for="SelectedAlertIndex" asp-items="@Model.Alert_Identifiers">
<option>Select one</option>
</select>
<br />
<input type="submit" name="LoadAlert" value="LoadAlert" />
</form>
请注意,如果未指定,则默认表单提交方法为GET
,如form element definition中所述:
方法=获取|发布[CI]
此属性指定将使用哪种HTTP方法 用于提交表单数据集。可能(不区分大小写) 值是“获取”(默认)和“发布”。
GET
方法将通过URL with query string传递表单值,因此您将获得如下所示的URL:
http://localhost:61453/alerts/AlertSelect?SelectedAlertIndex=2&LoadAlert=LoadAlert
由于找不到带有这两个查询字符串参数的HttpGetAttribute
操作方法,因此页面将“重置”并再次显示相同的表单,而不是返回另一个视图。