問題ASP.NET MVC模型綁定對我來說仍然是新的,我試圖瞭解它是如何工作的。現在,我似乎有問題的功能Html.Textbox()ASP.NET MVC2 - 與模型綁定和Html.Textbox()
具體而言,我有一個視圖,我在Html.Textbox設置爲「Get」和「Post」的值。它在「獲取」中設置正確,但在用戶在「發佈」期間提交了一個值之後,我會根據提交的其他值在內部更改其中一個值。
(我將根據其他基本驗證一個價值......我不知道這是否是這樣做的正確的方式...)
通過跟蹤,我可以看到,值實際上在模型和視圖中都發生了預期的變化,但是當它在「發佈」之後顯示在我的屏幕上時,該值不會隨着它被更改而顯示。相反,它是最初設定的。
這裏是我的簡單的例子:
的視圖顯示:
- 下拉的項目從的SelectList(預選爲「其他」)
- 一個只讀文本框(爲0的預加載值)
- 提交按鈕
用戶應該選擇從下拉列表中新的價值然後點擊提交。控制器中的「發佈」方法從下拉菜單中選取新值並更改只讀文本框中的值並重新顯示。
(是的,我最終會做這與jQuery,太...)
這裏是我的樣品模型類:
public class SampleSubmission
{
public string Name { get; set; }
public int Volume { get; set; }
public readonly SortedList<string, int> NameVolumeList = new SortedList<string, int>();
// Standard Constructor
public SampleSubmission()
{
NameVolumeList.Add("Sample1", 10);
NameVolumeList.Add("Sample2", 20);
NameVolumeList.Add("Sample3", 50);
NameVolumeList.Add("Other", 0);
this.Name = NameVolumeList.Keys[0];
this.Volume = NameVolumeList[Name];
}
// Copy Constructor
public SampleSubmission(SampleSubmission samSub) : this()
{
this.Name = samSub.Name;
this.Volume = NameVolumeList[Name];
}
}
這裏的控制器:
public class SampleSubmissionController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
SampleSubmission sampleSub = new SampleSubmission();
return View(sampleSub);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(SampleSubmission sampleSub)
{
SampleSubmission samSub = new SampleSubmission(sampleSub);
return View(samSub);
}
}
這裏的景觀:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MvcModelBindTest.Models.SampleSubmission>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<%= Html.DropDownList("Name", new SelectList(Model.NameVolumeList.Keys.ToList())) %>
<%= Html.TextBox("Volume",Model.Volume) %>
<input type="submit" name="pick" id="pick" value="Pick" /> <% } %>
</asp:Content>
關於爲什麼新值不顯示的任何想法?
編輯:
爲了解決這個問題,我讀通過「jfar」給出的鏈接,並提出了1行的變化。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(SampleSubmission sampleSub)
{
SampleSubmission samSub = new SampleSubmission(sampleSub);
// Reset Model Value
ModelState.SetModelValue("Volume", new ValueProviderResult(
samSub.Volume, "", System.Globalization.CultureInfo.CurrentCulture));
return View(samSub);
}
這絕對有效。不幸的是,這對我來說感覺像是一場嚴重的黑客攻擊。如果我必須更新多個字段的值,該怎麼辦?必須有一個更好的(更簡單的)方法來做到這一點。
編輯2:找到我的答案。見下文...
可能重複[如何清除與MVC HTML輔助定義文本框(http://stackoverflow.com/問題/ 3444994/how-to-clear-textboxes-defined-with-mvc-html-helpers) – jfar 2010-09-22 16:03:33