gpt4 book ai didi

c# - 如何使用不同类型的 ASP.NET MVC 访问 View 中的字段

转载 作者:太空宇宙 更新时间:2023-11-03 11:53:02 25 4
gpt4 key购买 nike

给定以下代码

操作方法

// Action for A
public ActionResult New(Ticket t, int knownLocation, string location) { ... }

// Action for B
public ActionResult Edit(Log log, int id, string assignTo, int knownLocation, string location) { ... }

观看次数

// Ticket.ascx
<%= Html.EditorFor(t => t.KnownLocation);

// A
<%@ Inherits="System.Web.Mvc.ViewPage<Models.Ticket>" %>
<%= Html.EditorForModel() %>

// B
<%@ Inherits="System.Web.Mvc.ViewPage<Models.Log>" %>
<%= Html.EditorFor(l => l.Ticket) %>

型号

class Log
{
...
Ticket Ticket { get; set; }
string Message { get; set; }
...
}
class Ticket
{
...
Importance Importance { get; set; }
string Name { get; set; }

// Please note the protected access level
Location KnownLocation { get; protected set; }
string Location { get; protected set; }

...
}

在 New ("A") 中,knownLocation 工作正常。在 Edit ("B") 中,knownLocation 抛出异常(在幕后):

The parameters dictionary contains a null entry for parameter 'knownLocation' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(TechHelp.Core.Models.Log, Int32, System.String, Int32, System.String)' in 'TechHelp.Mvc.Controllers.TicketsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

我如何访问该字段?请注意,它不能绑定(bind)到模型的属性。

最佳答案

如果您查看正在创建的 html,您应该会看到正在创建的输入的名称在每种情况下都是不同的。

如果你真的想直接从 POST 中获取结果,那么你需要确保你的 int knownLocation 与在第二种情况下创建的输入的名称相匹配(我怀疑它是 Ticket_KnownLocation,但我也怀疑您使用的是 MVC 2 预览版,因此它可能与您不同)。

无论如何,我会说您可能不想直接从 POST 中提取 knownLocation。如果 Controller 需要访问它,我真的建议在 Model 上公开它并让 ModelBinding 框架为您完成工作。然后,您可以使用 log.Ticket.KnownLocation 访问它。

关于c# - 如何使用不同类型的 ASP.NET MVC 访问 View 中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1563096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com