2013-10-25 100 views
1

我需要將文本框數據傳遞給控制器​​按鈕單擊操作。這裏是我的代碼:將按鈕單擊文本框值傳遞給控制器​​?

<input id="txt" type="text"> 
<button onclick="@Url.Action("MyAction", "Mycontroller", new {currencyCode=ViewBag .currencyCode,endDate=Model.StartDate, value entered in txt above})" > 

我不能在這裏使用表格。你能否建議我如何訪問/傳遞這個價值觀?

感謝您的幫助和指導。

+0

你的控制器只能與POST數據或GET一起工作嗎? –

回答

3

您可以使用類似

<div> 
    <input type='text' name='UnboundTextBoxName' /> 
</div> 

MVC將自動UnboundTextBoxName的價值,將該值插入相同名稱的參數。

2

您應該使用<form>標籤並將操作設置到您的控制器並在您的模型中設置一個位置來存儲數據。

+0

+1,對於一個好的建議。這將是理想的解決方案 – Satpal

6

下面的代碼將文本框的值發送到控制器的操作。

<input id="txt" type="text"> 
<button id="button">Click Me</button> 

@section Scripts { 
    <script type="text/javascript"> 
     $("#button").click(function() { 
      var txtVal = $("#txt").val(); 
      window.location = "@Url.Action("TheAction","TheController")" + 
           "/" + txtVal; 
     }); 
    </script> 
} 
+0

嗨,這很好,但文本沒有獲得傳入我的控制器方法。我怎樣才能調試這個函數來看看發生了什麼? – MoonKnight

+1

JavaScript代碼製作一個如下所示的URL:www.example.com/TheController/TheAction/TheText。如果控制器的「TheAction」方法有一個參數,它將以「TheText」爲參數。 RouteData也有「TheText」。 –

0

這將幫助你在文本框中輸入的值是反過來的url和部分打在你的控制器所需的操作中指定

<form id = "form1" runat="server"> 
    <asp:TextBox id= "txtbox" runat="server"></asp:TextBox> 
    <input type="button" id = "searchbtn" value="Search" onclick="srch_Click()"/> 
</form> 

<script type ="text/javascript" > 
function srch_Click() { 
     var host = window.location.host; 
     var txt = $("#txtbox").val(); 
     var path = "/CONTROLLER/ACTION/" + txt; 
     window.location.pathname = path; 
     var url = host + path; 
     window.location(url); 
    } 
</script> 

任何即興上面的代碼歡迎

相關問題