Javascript ajax post textbox text to ActionResult asp.net mvc

时光总嘲笑我的痴心妄想 提交于 2020-01-13 05:51:07

问题


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>

回答1:


You don't need to wrap in an additional object. Also you have invalid javascript. There's a trailing comma 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();
}


来源:https://stackoverflow.com/questions/21259290/javascript-ajax-post-textbox-text-to-actionresult-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!