Html
<input type="password" id="LoginPasswordText" title="Password" style="width: 150px" />
<input type="button" id="LoginButton1" value="Save" class="LoginButton1Class" onclick="LoginButton1OnClick" />
Json
var TextBoxData = {
Text: LoginPasswordText.GetValue(),
};
function LoginButton1OnClick() {
$.ajax({
url: "/Home/MyActionResult",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(TextBoxData),
success: function (mydata) {
alert("Success");
}
});
return true;
}
MyActionResult
public ActionResult MyActionResult(string Text)
{
return view();
}
Above codes(Html,Json,MyActionResult) works very well but it is json data.
I want to send above codes as ajax data.And i tried below code. However below code does not work , if i click to button , i can not send any data and there is nothing.Where i miss ?
<script>
function LoginButton1OnClick() {
var TextBoxData = {
Text: LoginPasswordText.GetValue(),
};
$.ajax({
type: "POST",
url: "Home/MyActionResult",
data: TextBoxData,
success: function () {
alert('success');
}
});
}
</script>
Html
<input type="password" id="LoginPasswordText" title="Password" style="width: 150px" />
<input type="button" id="LoginButton1" value="Save" class="LoginButton1Class" onclick="LoginButton1OnClick" />
Json
var TextBoxData = {
Text: LoginPasswordText.GetValue(),
};
function LoginButton1OnClick() {
$.ajax({
url: "/Home/MyActionResult",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(TextBoxData),
success: function (mydata) {
alert("Success");
}
});
return true;
}
MyActionResult
public ActionResult MyActionResult(string Text)
{
return view();
}
Above codes(Html,Json,MyActionResult) works very well but it is json data.
I want to send above codes as ajax data.And i tried below code. However below code does not work , if i click to button , i can not send any data and there is nothing.Where i miss ?
<script>
function LoginButton1OnClick() {
var TextBoxData = {
Text: LoginPasswordText.GetValue(),
};
$.ajax({
type: "POST",
url: "Home/MyActionResult",
data: TextBoxData,
success: function () {
alert('success');
}
});
}
</script>
Share
Improve this question
edited Jan 21, 2014 at 13:22
user3219315
asked Jan 21, 2014 at 13:17
user3219315user3219315
231 silver badge4 bronze badges
1 Answer
Reset to default 2You don't need to wrap in an additional object. Also you have invalid javascript. There's a trailing ma after the LoginPasswordText.GetValue()
call resulting in a javascript error. Also in order to retrieve the value of the input field you could use the .val()
function.
So simply send the value as-is:
<script>
function LoginButton1OnClick() {
var text = $('#LoginPasswordText').val();
$.ajax({
type: "POST",
url: "Home/MyActionResult",
data: text,
success: function () {
alert('success');
}
});
}
</script>
This will send the string value to the following controller action:
[HttpPost]
public ActionResult MyActionResult(string text)
{
return View();
}