首頁 > 後端開發 > C++ > 為什麼我的TextBoxfor在MVC中重定向後顯示' Latitude2”而不是' Latitude”?

為什麼我的TextBoxfor在MVC中重定向後顯示' Latitude2”而不是' Latitude”?

Mary-Kate Olsen
發布: 2025-02-01 08:21:10
原創
265 人瀏覽過

Why Does My TextBoxFor Display

> mvc textboxfor:初始與更新值

>

此示例在ASP.NET MVC應用程序中演示了一個常見的問題,其中顯示出意外的初始值而不是更新的值。 > TextBoxFor>讓我們檢查MVC操作並查看方案:>

控制器操作:

> view:

<code class="language-csharp">[HttpPost]
public ActionResult SomeInformation()
{
    var test1 = new DataSites { Latitude = "LATITUDE2" };
    return RedirectToAction("Index", test1);
}

[HttpPost]
public ActionResult Index(DataSites dataSiteList)
{
    if (dataSiteList.Latitude != null)
    {
        var test = new DataSites { Latitude = "LATITUDE" };
        return View(test);
    }
    return View(dataSiteList);
}</code>
登入後複製

模型:

<code class="language-csharp">@model miniproj2.Models.DataSites

<p>
    @Html.TextBoxFor(x => x.Latitude)
</p></code>
登入後複製

>問題:

>在導航至
<code class="language-csharp">public class DataSites
{
    public string Latitude { get; set; }
}</code>
登入後複製
(將緯度設置為“ latitude2”)並重定向到

>時,視圖顯示“ latitude2”,而不是預期的“ latitude” 。 /Home/SomeInformation>說明:Index

>帶有模型將數據傳遞為路由值。 然後使用此值(“ Latitude2”)將默認模型活頁夾填充。 即使操作試圖分配新值(“緯度”),現有>值也優先。

>解決方案: RedirectToAction ModelState有效地解決了兩種方法:Index ModelState 在分配新值之前,

>

clear ModelState:清除

  1. 避免模型綁定:直接在>操作中初始化一個新的ModelState實例,繞過模型完全綁定: Index
  2. 在這些解決方案之間進行選擇
取決於您是否需要從
<code class="language-csharp">[HttpPost]
public ActionResult Index(DataSites dataSiteList)
{
    ModelState.Clear(); // Add this line

    if (dataSiteList.Latitude != null)
    {
        var test = new DataSites { Latitude = "LATITUDE" };
        return View(test);
    }
    return View(dataSiteList);
}</code>
登入後複製
>操作中的其他目的訪問數據。 如果不是,則第二個解決方案(避免模型結合)更加干淨,更有效。 否則,清除
    是必要的。
  1. >

以上是為什麼我的TextBoxfor在MVC中重定向後顯示' Latitude2”而不是' Latitude”?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板