2016-10-22 37 views
1

控制器:@ Html.ListBox()和@ Html.DropDownList()如何保持asp.net mvc中的狀態?

public class HomeController : Controller 
      { 
       // 
       // GET: /Home/ 
       public ActionResult Index() 
       { 
        return View(); 
       } 
       [HttpPost] 
       public ActionResult Index(string list1) 
       { 
        return View(); 
       } 


      } 

視圖(使用默認配置):

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

@using (Html.BeginForm()) 
{ 

    @Html.DropDownList("list1", 
         new SelectList(new[] { "Item 1", "Item 2", "Item 3" })) 

    <input type="submit"/> 
} 
<br /> 
<br /> 

在DropDownList的選擇值和提交表格後我的申請有一個是以前同樣的狀態。例如,如果我在按下「提交」後選擇「項目3」,我已選擇「項目3」。它是如何工作的?

UPD:

我不想回避它,只是想了解它的工作。

+0

這是一個問題(意味着你不能修改你的下拉選擇項目),或者你問這是怎麼發生的? – Rajput

+0

不,我只想知道國家的工作機制如何,因爲我們知道「網絡無國籍」。可能是這個「幫手」使用ModelState,我不知道。 –

+1

請確認請求是否發送到提交''服務器' –

回答

0

從MVC來源:

SelectExtensions.cs:

..... 
    object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(fullName, typeof(string[])) : htmlHelper.GetModelStateValue(fullName, typeof(string)); 
..... 

HtmlHelper.cs:

internal object GetModelStateValue(string key, Type destinationType) 
     { 
      ModelState modelState; 
      if (ViewData.ModelState.TryGetValue(key, out modelState)) 
      { 
       if (modelState.Value != null) 
       { 
        return modelState.Value.ConvertTo(destinationType, null /* culture */); 
       } 
      } 
      return null; 
     } 

那麼,這意味着Action發送「ModelState」來查看和控制(我知道它不是正確的定義)使用「ModelState」來填充它們自己。

1

在您的[Post]處理程序中,您不會在任何地方重定向並直接返回視圖。因此,這些值仍然存在,因爲它們仍然處於模型狀態。

一個常見的模式是redirect[Get]處理程序成功Post後,在這種情況下值不會持續。

+0

[鏈接](https://youtu.be/WHkoLQjcR7Q)與get相同。 –

+0

@VladMelnik它也可能是瀏覽器在頁面刷新後恢復控件中的值。在視圖中設置斷點並查看它是否在服務器端的模型狀態中有值。 – GSerg

+0

[是的,它是(] http://image.prntscr.com/image/6b73430b8bf14614b403c9eb069d4502.png) –

相關問題