gpt4 book ai didi

asp.net-mvc - 如何在我的 View 模型类中使用名为 'Model' 的属性?

转载 作者:行者123 更新时间:2023-12-04 23:45:33 25 4
gpt4 key购买 nike

我有一个非常简单的 View 模型类和一个强类型 View (它使用这个类作为 View 模型)。

public class MatchModelRequest
{
public string Country { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public DateTime RegDate { get; set; }
public int EnginePower { get; set; }
public string FuelType { get; set; }
public string BodyType { get; set; }
public string Transmission { get; set; }
public int Cc { get; set; }
public int Doors { get; set; }
}

问题是那里有一个名为“Model”的属性。

当我在 View 中执行此操作时:
<%= Html.EditorFor(m => m) %>

我得到了一个很好的表格,它具有 MatchModelRequest 的所有属性.完全没有问题(模型绑定(bind)也没有,在 MatchModelRequest 对象中检索值时)。

但是当我在 View 中将它们拆分为这样的单个字段时:
<div class="editor-field">
<%= Html.TextBoxFor(m => m.Model)%>
<%= Html.ValidationMessageFor(m => m.Model)%>
</div>

我得到一个未处理的异常 System.ArgumentException: Value cannot be null or empty , 在上面使用 m.Model 的第一行。

我想这与 Model 有关位于 ViewPage 的房产,但我看不出我能做些什么来解决这个问题,而只是给该属性取另一个名字。

在我的情况下,现在可以为该属性提供另一个名称,但我想将其命名为“模型”。并且并不总是可以更改模型的属性。

编辑

我一直在进一步调查这个问题,显然出错的部分位于 GetExpressionText(LambdaExpression expression) 方法中的 System.Web.Mvc.ExpressionHelper 中。有以下几行:
// If it starts with "model", then strip that away
if (nameParts.Count > 0 && String.Equals(nameParts.Peek(), ".model", StringComparison.OrdinalIgnoreCase)) {
nameParts.Pop();
}

这就是实际的“模型”部分被剥离的地方......所以我想这是设计使然,然后我没有其他选择来重命名我的属性(property)?

仍然欢迎提出建议。

顺便说一句,这是 MVC 2。有人可以检查这段代码是否仍然存在于 MVC 3 中吗?

最佳答案

是的,没错。我查看了 MVC 3 RTM 源代码,有两个地方从表达式中删除了“模型”。第一个是当我们使用像 @Html.TextBoxFor("model") 这样的字符串表达式时。 .

    public static string GetExpressionText(string expression) {
return
String.Equals(expression, "model", StringComparison.OrdinalIgnoreCase)
? String.Empty // If it's exactly "model", then give them an empty string, to replicate the lambda behavior
: expression;
}

另一个在 GetExpressionText(LambdaExpression expression)正如你之前所说。
    // If it starts with "model", then strip that away
if (nameParts.Count > 0 && String.Equals(nameParts.Peek(), ".model", StringComparison.OrdinalIgnoreCase)) {
nameParts.Pop();
}

所以,我认为现在最好的解决方案是重命名你的属性(property):)

更新:实际上,它适用于 Mvc3,我只是对其进行了测试。代码中有一个修复,请参见:
else if (part.NodeType == ExpressionType.Parameter) {
// Dev10 Bug #907611
// When the expression is parameter based (m => m.Something...), we'll push an empty
// string onto the stack and stop evaluating. The extra empty string makes sure that
// we don't accidentally cut off too much of m => m.Model.
nameParts.Push(String.Empty);
part = null;
}
else {
break;
}

关于asp.net-mvc - 如何在我的 View 模型类中使用名为 'Model' 的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5067730/

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