gpt4 book ai didi

asp.net-mvc - 未在 View 中使用的 MVC 2 模型属性返回为 null 或空

转载 作者:行者123 更新时间:2023-12-02 02:27:27 25 4
gpt4 key购买 nike

我遇到的问题是当我将填充对象传递给未显示所有属性的 View 时。

public ActionResult Edit(Guid clientID)
{
Property property = PropertyModel.GetPropertyDetails(clientID);
return View("Edit", "Site", property);
}

查看:

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<WebFrontend.ViewModels.Property>" %>

<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true, "Property update was unsuccessful. Please correct the errors and try again.") %>

<fieldset>
<legend>Edit Account: <%: Model.ClientAccountNo %></legend>

<div class="editor-label">
<%: Html.LabelFor(model => model.ClientName)%>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.ClientName)%>
<%: Html.ValidationMessageFor(model => model.ClientName)%>
</div>

<p>
<input type="submit" value="Update Property" />
</p>
</fieldset>

<% } %>

提交时,Property 对象会传递给此 Controller 方法,但 View 中未使用的所有属性均为 null 或空,包括提交前 View 中存在的 Model.ClientAccountNo。

[HttpPost]
public ActionResult Edit(Property property)
{
if (ModelState.IsValid)
{
bool success = PropertyModel.UpdateProperty(property);
if (success)
{
// property has been updated, take them to the property details screen.
return RedirectToAction("Details", "Property", new { clientID = property.ClientID });
}
else
{
ModelState.AddModelError("", "Could not update property.");
return View("Activate", "Site", property);
}
}
// If we got this far, something failed, redisplay form
return View("Edit", "Site", property);
}

我在网上找不到任何类似的东西,如果能解释为什么会发生这种情况以及如何解决它,我们将不胜感激。

最佳答案

这就是 MVC 的工作方式——它试图从路由、表单和查询字符串中的值构造一个 Action 参数类型的对象。在您的情况下,它只能获取表单集合中的值。它对您存储在数据库中的值一无所知。

如果您只对某些属性感兴趣,您最好只打开这些属性来制作特定的 View 模型 - 然后您可以验证这种特定情况。

如果您将值存储在隐藏字段中,请记住这些值可以被操作 - 如果这是一个问题,请务必使用仅打开可编辑字段的特定 View 模型。

关于asp.net-mvc - 未在 View 中使用的 MVC 2 模型属性返回为 null 或空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5328270/

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