簡體   English   中英

asp.net mvc。 通過Get(表單)發送數據並在標簽中返回成功?(如何將數據發送和返回到同一視圖)

[英]asp.net mvc. Sending data through Get (form) and returning success in a label?(how to send and return data to the same view)

我正在努力學習 .net mvc 是如何工作的。 我一直在嘗試制作一種字謎檢查器,但在此之前我正在輸入並通過 GET(表單)發送到控制器,並且想要檢查一個單詞是否與另一個相同(ex word1 ==詞 1)。 如果這是真的,我想將“成功”作為要寫入標簽的字符串發送回視圖。 所以我有一個問題。 首先我知道如何通過 get 發送數據,到目前為止我檢查了一個詞是否等於某物,如果這是真的那么我重定向到 index.html 。 我不知道如何將“成功”發送回同一視圖(如果可能,不使用 ajax)並將其寫在標簽中,因此我輸入了一個文本,如果這與我的相同,那么它會在下面說成功控制器:

       {
           if ( word == "word1")
           {
               //return HttpNotFound();
               return RedirectToAction("Index");

           }
           return View();
       }

風景:

@{
    ViewBag.Title = "CheckAnagram";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>CheckAnagram</h2>




@using (Html.BeginForm("CheckAnagram", "Anagrams", FormMethod.Get, new { @class = "navbar-form navbar-left" }))
{
    <div class="form-group">
        @Html.TextBox("word", null, new { @class = "form-control", @placeholder = "Check for anagrams" })
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
}

我知道我可以發送一個模型來查看但是當我重新加載頁面時它會再次發送它,所以我無法理解如何使其正常工作,正常的方法是什么?

您可以使用TempData將模型數據傳遞給重定向請求。 您可以傳遞字符串、int、Guid 等簡單類型。如果您想通過 TempData 傳遞復雜類型的對象,您可以將對象序列化為字符串並傳遞它。 在您的場景中,您可以這樣做:

{
 if ( word == "word1")
 { 
  TempData["myresult"] = "Word match";
  //return HttpNotFound();
  return RedirectToAction("Index");
 }
 return View();
}

您的Index方法將如下所示:

public ActionResult Index()
{
    if (TempData["myresult"] !=null)
    {
        var myresult= TempData["myresult"];
        ViewBag.myresult=myresult;
    }
    return View();
}

在您的Index視圖中,您可以簡單地檢索要顯示的ViewBag值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM