2014-09-04 61 views
0

Hy everybody, 在我的Razor View頁面中,我有一個文本輸入。我想通過使用「onchange」事件調用控制器,並將我的輸入值添加到包含在我的Razor模型中的列表中。剃刀:將輸入文本+模型傳輸到控制器

這是我的html頁面:

<html> 
<head> 
    <meta name="viewport" content="width=device-width" /> 
    <title>MyForms</title> 
</head> 
<body> 
    <label>Code</label> 
    <form method="post" action=""> 
     <input name="NPItem" maxlength="11" autofocus onkeypress="return isNumberKey(event)"  onchange="location.href = '@Url.Action("addtoList", "MyController", new { formsData =  Newtonsoft.Json.JsonConvert.SerializeObject(Model) })';"/> 
    </form> 
    <table border="1" id="listeNPAI"> 
     <tr> 
      <th>Index</th> 
      <th>Value</th> 
     </tr> 
     @{ 
      foreach (Tuple<string, string> item in Model.list) { 
       <tr> 
        <td>@item.Item1</td> 
        <td>@item.Item2</td> 
       </tr> 
      } 
     } 
    </table> 
</body> 
</html> 

這就是我所謂的控制器操作:

public ActionResult addtoList(string formsData) { 
      formsData _form = Newtonsoft.Json.JsonConvert.DeserializeObject<ModelClass>(formsData); 
      string input = Request["NPItem"]; 
      if (input == null) { input = ""; } else { input = input.Trim(); } 
      if (input.Length == 11) { 
       _form.list.Add(new Tuple<string, string>(input.Substring(0, 5), input.Substring(6))); 
      } 
      return View("FormulaireNPAI", _form); 
     } 

我在我的控制器動作輸入文本值添加到列表中。問題是輸入總是'==空'(因爲沒有提交)。但是,當我按下Enter鍵時,它會起作用。

幫助,請 THKS提前

+0

我認爲當你需要刷新模型然後更新視圖時,你需要對服務器進行AJAX調用。 – Greenonion 2014-09-04 15:30:09

回答

0

你可以做這樣的事情:

$("#element").on("click", function() { 
      $.ajax({ 
       url: "action", 
       type: "GET", 
       data: { data } 
      }) 
      .done(function(partialViewResult) { 
       $("#yourViewWrapper").html(partialViewResult); 
      }); 
     }); 

即由AJAX調用,當你需要再刷新視圖。

+0

謝謝你的回答。你能指定請問我可以把這個代碼放在哪裏?我真的不知道。 – makertoo 2014-09-04 15:49:05

+0

您應該將javascript添加到您的頁面。當然,你應該用正確的數據修改它。 – Greenonion 2014-09-04 16:15:31