简体   繁体   中英

Send data to ajax controller

The program does the following steps:

  1. The user clicks on Change Address
  2. The button disappears, another button appears - Save.
  3. Next, the program should read the data from the input and send it via ajax to the controller method.

But nothing works. When I put everything in one <script> tag, the first button also stops working. Help

The problem is that even the buttonSetAddress button does not perform the function. It starts working only after I remove everything else from <script>

<div class="form-group">
    <label>Адресс</label>
    <input class="form-control" id="AddressInput" type="text" placeholder="@ViewBag.User.Address" readonly /><br />
    <button type="button" class="btn btn-primary" id="buttonSetAddress">Изменить</button>
    <button type="button" class="btn btn-success" id="buttonSaveAddress" onclick="SaveAddress()" hidden>Сохранить</button>
</div>

js and ajax

<script type="text/javascript">
    document.getElementById('buttonSetAddress').onclick = function AddressInputSet() {
        document.getElementById('AddressInput').removeAttribute('readonly');
        document.getElementById('buttonSetAddress').hidden = 'true';
        document.getElementById('buttonSaveAddress').removeAttribute('hidden');
        alert('sdfgdfg');
    };
    document.getElementById('buttonSaveAddress').onclick =  function SaveAddress() {
        var data = JSON.stringify( {
            userId: @ViewBag.User.Id,
            address: document.getElementById('AddressInput').value
        });

        $.ajax({
            type: 'POST',
            url: '/Account/ResetAddress',
            data: data,
            dataType: JSON,
            success: function () {
                document.getElementById('buttonSaveAddress').hidden = 'true';
            },
            error: function () {
                alert('Error');
            }
        });
    };
</script>

Controller

[HttpPost]
public async void ResetAddress(string userId, string address)
{
    var user = await _userManager.FindByIdAsync(userId);
    user.Address = address;
    await _userManager.UpdateAsync(user);
}

try add quote to this value

var data = {
            userId: '@ViewBag.User.Id', // here
            address: document.getElementById('AddressInput').value
        };
var data =JSON.stringify( {
            userId: '@ViewBag.User.Id', // here
            address: document.getElementById('AddressInput').value
        });

You have to use JSON.stringify to turn you object to json.

and also yo must set content type in ajax

contentType is the type of data you're sending, so application/json; charset=utf-8 application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8 application/x-www-form-urlencoded; charset=UTF-8 , which is the default.

dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.

Since your action return void , you could not set the dataType as JSON.

Try to use below code which works well(Make sure the url is correct)

<div>
<label>Адресс</label>
<input class="form-control" id="AddressInput" type="text" placeholder="@ViewBag.User.Address" readonly /><br />
<button type="button" onclick ="AddressInputSet()"class="btn btn-primary" id="buttonSetAddress">Изменить</button>
<button type="button" onclick="SaveAddress()" class="btn btn-success" id="buttonSaveAddress"  hidden>Сохранить</button>
</div>
@section Scripts{
<script type="text/javascript">
    function AddressInputSet() {
        document.getElementById('AddressInput').removeAttribute('readonly');
        document.getElementById('buttonSetAddress').hidden = 'true';
        document.getElementById('buttonSaveAddress').removeAttribute('hidden');
        alert('sdfgdfg');
    };
   function SaveAddress() {
        var data ={
            userId: @ViewBag.User.Id,
            address: document.getElementById('AddressInput').value
        };

        $.ajax({
            type: 'POST',
            url: '/Account/ResetAddress',
            data: data,
            //contentType: "application/x-www-form-urlencoded; charset=utf-8",
            //dataType: JSON,
            success: function () {
                document.getElementById('buttonSaveAddress').hidden = 'true';
            },
            error: function () {
                alert('Error');
            }
        });
    };
</script>
}

Action:

[HttpPost]
public async void ResetAddress(string userId, string address)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM