Send data to ajax controller - c#

The program does the following steps:
The user clicks on Change Address
The button disappears, another button appears - Save.
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);
}

contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is 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)

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

Related

Asp.Net - How to call ActionResult with ajax

I want to click "2" Ajax will call ActionResult and put new question up but not rerun page
i have been trying two day but it haven't worked
People help me, please
ActionResult:
[HttpPost]
public ActionResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return View(cauhoi);
}
Function Ajax:
<script>
function loadcauhoi(num) {
$.ajax({
dataType: "Json",
type: "POST",
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
In HTML:
<li>
1
</li>
enter image description here
Thanks for reading
I changed but it dont work!!
I learned it myself so it was hard to get started
ActionResult:
[HttpPost]
public ActionResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return PartialView(cauhoi);
}
Function Ajax:
<script>
function loadcauhoi(num) {
$.ajax({
dataType: "Html",
type: "POST",
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#baitetstiq').html(a);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
Full HTML:
<div class="col-md-9" style="border-top-style:double;
border-top-color:aquamarine;
border-top-width:5px; margin-left:-15px">
<p style="text-align:center">
<b>Thời Gian Còn Lại Là:xxx</b>
</p>
<div id="baitestiq"></div>
#foreach(var item in Model)
{
<div class="baitest">
<div class="ques">
<img src="~/Hinh_Cauhoi/#item.Cauhoi" />
</div>
<div class="anw">
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn1" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn2" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn3" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn4" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn5" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn6" />
</div>
</div>
<div class="numbertest">
<ul>
<li>
1
</li>
</ul>
</div>
1st you need to return a partial view.
2nd you need to make a get ajax request and not a post
3rd you need to test first the result of #Url.Action("BaiTestIQ","TestIQ"), translate this to a URL, directly to make sure it returns the expected results without the ajax call to avoid getting into sideways with routing etc. see this for example
See a working example here
Update:
I see it now, you changed dataType: "Html"
You need to change several things:
1. The method is not changing any state so it should not be declared as a post method. You need to remove [HttpPost] attribute.
You need to be aware of ajax parameters contentType and dataType. From the documentation: contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8'). This specifies what type of data you're sending to the server. And dataType (default: Intelligent Guess (XML, json, script, or HTML)) specifies what jQuery should expect to be returned. In your case, it should be 'json' because you are using the result return from a LINQ query.
So the method might look like:
public JsonResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return Json(cauhoi.ToList(), JsonRequestBehavior.AllowGet);
}
3. Moving to the ajax call:
<script>
function loadcauhoi(num) {
$.ajax({
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
type: "GET",
cache: false,
dataType: "json",
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
**But I'd like to suggest another approach using a ViewModel with a partial view because serializing JSON data can sometimes get you errors. A quick tutorial

Sending simple type from HTML form to ASP API

I am having troubles with sending a simple double number from form to ASP API.
When I submit the form, I firstly need to remove Submit button to avoid sending a redundant 'submit=Submit' value to API controller.
As I have read in this article, I set the name of my input field to be empty. So if I check the http request in Developer mode, the body of sent data looks like so '=value'. My method parameter is decorated with [FromBody] attribute.
Even with all this, the controller method does not get the value. It is allways zero.
What to do?
My form looks like so:
<form action="#Url.Action("Temperature","Api")" method="post" >
<input type="number" name=" " step="0.25"/>
<input type="submit" name="submit" />
</form>
</div>
<script>
$("form").submit(function () {
$(this).children('[name="submit"]').remove();
});
</script>
The controller:
// POST: api/Temperature
public void Post([FromBody]double value) //FormDataCollection data
{
Temperature newEntry = new Temperature() { Timestamp = DateTime.Now, Value = value};
try
{
db.Temperatures.Add(newEntry);
db.SaveChanges();
}
catch(Exception e)
{
Debug.WriteLine(e.Message);
}
}
Try Ajax...
Change your Html little bit like this:
<div>
<input type="number" id="number" name=" " step="0.25"/>
<input type="button" id="submit" name="submit" />
</div>
Then:
$(document).on('click', '#submit', function () {
$.ajax({
type: 'POST',
url: '/ControllerName/Post',
data: {
value: JSON.stringify($('#number').val())
},
success: function (data) {
alert(data);
},
error: function (data) {
alert("An Issue has occured");
}
});
})
Also your controller input parameters would be like:
public void Post([FromBody]string value) //convert string to double later within method

Upload file in MVC Core via Ajax

I need to upload file in MVC Core via Ajax post request.
My Index.cshtml
<input id="addLogoFile" type="file" class="form-control" accept="image/png" />
<input id="addLogoText" type="text" class="form-control" placeholder="Logo title" />
<button type="button" id="addLogoBtn" class="btn btn-sm btn-success"><span class="glyphicon glyphicon-repeat"></span></button>
$("#addLogoBtn").click(function (e) {
e.preventDefault();
var fileInput = $("#addLogoFile");
var formData = new FormData();
var fileTitle = $("#addLogoText").val();
var file = fileInput[0].files[0];
formData.append(file.name, file);
var request = $.ajax({
url: '#Url.Action("AddLogo", "OrganizationManagement")',
type: "POST",
cache: false,
processData: false,
data: { image: formData, imageName: file.name, title: fileTitle },
datatype: "json"
})
request.done(function (data) {
var logos = $("#Logos");
logos.empty();
$.each(data, function () {
logos.append($("<option />").val(this.Value).text(this.Text));
})
})
request.fail(function (e) {
$("#addLogoText").val(e.responseText);
})
})
My ExampleController.cs:
[HttpPost]
public async Task<JsonResult> AddLogo(IFormFile image, string imageName, string title)
{
//code doesn't matter, null in image, imageName and title
}
The problem, is that image, imageName, title are always null. How should I fix it?
EDIT
If I add contentType: false i have this error in my Network Debugger: The server encountered an unexpected condition that prevented it from fulfilling the request

How to set Html class with a javascript function?

i display 4 buttons for each elements in a list.
i want to know which button has data inside so i create an ActionResult and this returns true if contains data.
[HttpPost]
public ActionResult TieneNotificacion(string Pnombre, string Pcorreo1, string Pprefijo)
{
var lista = agp.CC15_EscalaMandoPorUsuario(Pnombre,Pcorreo1,Pprefijo);
if(lista != null){
return Json(true);
}
else{
return Json(false);
}
}
in the view i want to set the button class "btn btn-xs" if the method return false and "btn btn-xs btn-info" if return true.
$(document).ready(function () {
function tieneNotificacion(Nombre,Correo1,Prefijo){
$.ajax({
type: "POST",
url: "/CentralSoluciones/TieneNotificacion",
data: { Pnombre: Nombre,
Pcorreo1: Correo1,
Pprefijo: Prefijo },
success: function (data) {
if (data) {
return "btn btn-xs btn-info"
}
else {
return "btn btn-xs"
}
}
});
}
});
and the html tag is like that:
<a href="#Url.Action("Detalles", new { Pnombre= item.Nombre, Pcorreo1=item.Correo1, Pprefijo=list.Prefijo })"
class=tieneNotificacion(#item.Nombre,#item.Correo1,#list.Prefijo)>
<span>#list.Prefijo</span>
</a>
You can set the class for your button within the AJAX call.
Suppose you have these buttons
<input type="button" />
<input type="button" />
<input type="button" />
Update your javascript to
$(document).ready(function () {
function tieneNotificacion(Nombre,Correo1,Prefijo){
$.ajax({
type: "POST",
url: "/CentralSoluciones/TieneNotificacion",
data: { Pnombre: Nombre,
Pcorreo1: Correo1,
Pprefijo: Prefijo },
success: function (data) {
if (data) {
$( ":button" ).addClass("btn btn-xs btn-info");
//To set a class completely, instead of adding one or removing one.
// use this $( ":button" ).attr('class','btn btn-xs btn-info');
}
else {
$( ":button" ).addClass("btn btn-xs");
//To set a class completely, instead of adding one or removing one.
// use this $( ":button" ).attr('class','btn btn-xs');
}
}
});
}
});
JSFiddle

Getting a local variable value using jQuery

I have a little problem when trying to get the value of a local int variable on a view, using jQuery. So, I have a the main view, and as you can see in the code below, I use a partial view named "_Result", when I try to get the value of indexPage by handling the click event of a button in the partial view, I get 0, event if I initialize my variable by another value(5 for example). Any idea why ?
Thanks in advance
My view :
#model System.Data.DataTable
#{var pageIndex = 5;}
<div>
<div>
<span>Téléphone ?</span>
<input id="idTxTel" type="text" name="txTelephone"/>
<input id="idBnSearch" type="submit" value="Chercher" name="bnSearch"/>
</div>
#Html.Partial("_Result", Model)
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#idBnSearch").click(function () {
//The right value (5)
alert('#pageIndex');
var telValue = $("#idTxTel").val();
var methodUrl = '#Url.Content("~/Search/GetReverseResult/")';
'#{pageIndex = 0;}'
doReverseSearch(telValue, '#pageIndex', methodUrl);
});
$("#bnNextPage").live("click", function ()
{
//Not th right value (0)
alert('#pageIndex');
});
});
</script>
My doReverseSearch method :
function doReverseSearch(telValue, pageIdx, methodUrl)
{
$.ajax(
{
url: methodUrl,
type: 'post',
data: JSON.stringify({ Telephone: telValue, pageIndex: pageIdx }),
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#result').replaceWith(data);
},
error: function (request, status, err) {
alert(status);
alert(err);
}
});
}
My partial view :
<div id="result">
<h2>Résultat de la recherche</h2>
<div>#ViewBag.CountResult entreprises trouvées</div>
#if(Model != null)
{
foreach (DataRow row in Model.Rows)
{
<h3>#row["CompanyName"]</h3>
}
}
<hr />
<div>
<span>Page N sur M</span>
<input id="bnPreviousPage" type="submit" value="Précédant" name="bnPrevious"/>
<input id="bnNextPage" type="submit" value="Suivant" name="bnNext"/>
</div>
</div>
Razor inside javascript has to be wrapped in a block
so you can do this:
<script>
// global value for page
<text>
var myPage = #pageIndex;
<text>
</script>
what would be far easier is give the button an attribute of data-page and ask for attribute in click event:
<button data-page="#("pageIndex")" id="myButt" />
$("#myButt").on("click",function(e){
var pageIndex = $(this).attr("data-page");
alert(pageIndex);
});

Categories