2014-04-18 46 views
1

獲取MVC表單數據使用JavaScript

@using (Html.BeginForm()) 
    { 
     <div class="editor-label"> 
      @Html.LabelFor(m => m.Title) 
     </div> 
     <div class="editor-field"> 
      @Html.TextBoxFor(m => m.Title) 
      @Html.ValidationMessageFor(m => m.Title) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(m => m.Description) 
     </div> 
     <div class="editor-field"> 
      @Html.TextAreaFor(m => m.Description) 
      @Html.ValidationMessageFor(m => m.Description) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(m => m.Icon) 
     </div> 
     <div class="editor-field"> 
      @Html.RadioButtonFor(m => m.Icon, "http://maps.google.com/mapfiles/ms/icons/red-pushpin.png", new { @checked = "checked" }) <img src="http://maps.google.com/mapfiles/ms/icons/red-pushpin.png" alt="red pusphin" /> 
      @Html.RadioButtonFor(model => model.Icon, "http://maps.google.com/mapfiles/ms/icons/red-pushpin.png") <img src="http://maps.google.com/mapfiles/ms/icons/blue-pushpin.png" alt="blue pushpin" /> 
     </div> 

    } 

我如何使用JavaScript檢索數據?

我嘗試以下,但它似乎並不奏效:

document.getElementsByName('Title').value; 
+0

關於使用模型進行綁定控制,瀏覽器會根據模型創建id,使用該id定義您自己的id和訪問值。 –

+0

你的意思是獲取表單提交或頁面加載的數據 – super

回答

1

試試這個

document.getElementById('Title').value; 

檢查這個小提琴

http://dotnetfiddle.net/t67Q3G

+0

它是getElementById不是元素,我已經嘗試過,值被傳遞是「」 – rikket

+0

@rikket檢查編輯答案 – Nilesh

+0

小提琴工作,因爲我失蹤「」,而不是'' – rikket

0

所有控件定義ID如:

@Html.LabelFor(m => m.Title,new{@ID="YOUR ID"}) 

度日ID值:

$("#YOUR ID").val(); 
0

如果你需要從模型到JavaScript中的值,你可以簡單地做到這一點。

function showpopup() 
{ 
    var model = @Html.Raw(Json.Encode(Model)); 
    alert(model.Title); 
}