簡體   English   中英

使用JavaScript從HTML文本框中獲取價值

[英]Get value from html textbox with javascript

我創建了一個ASP.NET MVC應用程序,並希望在將其發送回控制器之前在文本框中使用值進行一些“填充”。

所以我有一個形式的文本框:

using (Html.BeginForm("HandleForm","Home")
{
    <p>Enter Value<p>
    @Html.TextBox("amount")
    <input type="submit" value="Submit" />
}

通常我會在JS中使用類似的方法:

var value = document.getElementById(ID).value;

那么如何使用HTML Helpers來做到這一點? 可以給這個文本框一個ID嗎?

您不能為此獲得HTML Helper,但這可能會對您有所幫助。

var value = document.getElementById('@Html.Id("amount")').value;

使用@Html.Id() HTML Helper,您將獲得該特定viewData的ID

當然,您可以將IdClass和各種Html attributes分配給任何Html Helper因為這些Helper被解析為普通的html標簽。

例如

@Html.TextBoxFor(m=>m.amount,new { id = "txtAmount", class="anyClass" })

or

@Html.TextBox(m=>m.amount,null,new { id = "txtAmount", class="anyClass" })

這被解析為

<input id="txtAmount" name="amount" class="anyClass" type="text" />

然后在javascript中,您可以按以下方式訪問此控件的值

  var value = document.getElementById("txtAmount").value;

我們可以在mvc中使用html helper時指定其他html屬性

http://msdn.microsoft.com/en-us/library/dd493049(v=vs.118).aspx

html屬性被指定為簡單對象,例如

new { id = "text1", maxlength="20", size="15" }

方法簽名

public static MvcHtmlString TextBox(
    this HtmlHelper htmlHelper,
    string name,
    Object value,
    Object htmlAttributes
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM