2

I have created an ASP.NET MVC app and would like to do some "stuff" with a value in the textbox before its sent back to the controller.

So I have a textbox in a form:

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

normally i would use something like this in JS:

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

So how would I do this with the HTML Helpers? is it possible to give this textbox an id?

3
  • You can "alter" the value of the textbox only server side, before it gets sent to the client. There is no way to access it client side, using helpers. Commented Jan 27, 2014 at 10:45
  • I dont want to alter the value just get the value and say put it into a javascript variable, is that possible Commented Jan 27, 2014 at 10:49
  • If the value is "known" server side, then yes: var myVar = '@Model.MyVarValue'; (you might have to play with Html.Raw(). If the value is written by the user (i.e. after the page gets rendered), you need JavaScript to get it. Commented Jan 27, 2014 at 10:52

3 Answers 3

1

You can't get an HTML Helper for that, but this might help you.

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

using the @Html.Id() Html Helper you will get the id of that specific viewData

Sign up to request clarification or add additional context in comments.

Comments

0

we can specify additional html attributes when using html helpers in mvc

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

The html attributes are specified as simple object eg

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

Method Signature

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

Comments

0

Ofcourse you can assign Id, Class and various Html attributes to any Html Helper as these helpers are parsed to normal html tags.

E.g

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

or

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

This is parsed to

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

Then in javascript you can access value of this control as

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

2 Comments

by adding the id as you have shown its put the { id = "txtAmount" } into the text box?
check update use TextBoxFor or change overload for TextBox

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.