I have an array which as the number(Id's of some tags) and I am passing this array to the action method using ajax call when this array passed to the controller action method(RawTagCreation) and then the numbers in this arrays are used to get data from database and then pass to another ViewModel object (rawTagVMs) and then I am returning the partial view with this ViewModel object. The problem is that the partial view is not showing?
Basically success event of ajax call is also not fired.
function selectedValues() {
var datas = [];
$('#search_to option').each(function () {
datas.push($(this).attr('value'));
});
console.log(datas);
if (datas.length > 0) {
$.ajax({
url: "#Url.Action("RawTagCreation", "SourceTagMapping")",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ 'selectedTags': datas }),
success: function (data) {
debugger;
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
}
else {
alert('Please Select One or More Raw Tags')
}
}
The action method is given here
public ActionResult RawTagCreation(int[] selectedTags)
{
List<RawTagVM> rawTagVMs = new List<RawTagVM>();
if (ModelState.IsValid)
{
foreach (var item in selectedTags)
{
var OldSourecTag = db.Real_Raw_Points.Where(x => x.Source_Tag_Id_Fk == item).FirstOrDefault();
var OPCTag = db.OPC_SourceTags.Where(x => x.Source_Tag_Id == item).FirstOrDefault();
if (OldSourecTag == null)
{
RawTagVM objToInsertRawTags = new RawTagVM();
objToInsertRawTags.Source_Tag_Id_Fk = item;
objToInsertRawTags.R_Tag_Name = "Provide Tag Name";
rawTagVMs.Add(objToInsertRawTags);
}
}
return PartialView("_Update_TagNames", rawTagVMs);
}
return View();
}
PartialView is here
#model List<OmniConnect.ViewModel.RawTagViews.RawTagVM>
<div class="modal-header">
<h3 class="modal-title" id="exampleModalLabel">Update The Raw Tag Names</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="Confirm()">Confirm Update</button>
</div>
when you try ajax call
you can't return partial view
if you want return a view you must use form like Html.Beginform
and submit
if you want return success method you must return a value may be string
and append it to a tag
public ActionResult RawTagCreation(int[] selectedTags)
{
List<RawTagVM> rawTagVMs = new List<RawTagVM>();
if (ModelState.IsValid)
{
return Json("<div>any view</div");
}
return json("");
}
and then you can use like this:
$.ajax({
url: "#Url.Action("RawTagCreation", "SourceTagMapping")",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ 'selectedTags': datas }),
success: function (data) {
debugger;
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
Related
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
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
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
I'm trying to get and pass my ViewModel to my Json method doing the stuff like this :
In my view :
<input type="button" id="suggestionBtn" title="Suggestion" onclick ="location.href='#Url.Action("GetNextAppointment", "Home", new { svm = Model })'" />
In my Controller :
public JsonResult GetNextAppointment(SuggestionViewModel svm)
{
return Json(svm, JsonRequestBehavior.AllowGet);
//this is just for testing
}
While debugging, I found out that my svm is null. I tried to replace it by a string parameter and hard coding the value in my view and this works. So, I don't know very much where is the problem.
Any idea guys?
EDIT : Code edited to use jQuery AJAX
My view's now like this :
#model AstellasSchedulerV2.Models.SuggestionViewModel
<div class="rightPanel">
#using (Html.BeginForm("NewAppointment", "Home", FormMethod.Post, new { #id = "form_ValidateAppointment" }))
{
#Html.Hidden("stringParam","")
<fieldset>
<div>
Patch Anti-douleur Corps #Html.CheckBoxFor(s => s.PADC, new { #class = "checkbox", #id = "chbxPADC" })
</div>
<br />
<div>
Patch Anti-douleur Pied #Html.CheckBoxFor(s => s.PADP, new { #class = "checkbox", #id = "chbxPADP" })
</div>
<br />
Click me
</fieldset>
}
</div>
<script type ="text/javascript">
$(document).ready(function () {
$("#ClickMe").click(function () {
var o = new Object();
o.PADC = $("#chbxPADC").val();
o.PADP = $("#chbxPADP").val();
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(o),
success: function (data) { alert(data.PADC); },
failure: function (errMsg) { alert(errMsg); }
});
});
</script>
Here goes the solution, Lets say you have your viewmodel this way -
public class SuggestionViewModel
{
public bool PADC { get; set; }
public bool PADP { get; set; }
}
Then you have a View in the following way. Here I used JQuery to make a POST request to GetJson Controller Action. I constructed a JavaScript Object and then serialized it to Json. Then finally passed the Json string to Controller Action.
<fieldset>
<div>
Patch Anti-douleur Corps #Html.CheckBoxFor(s => s.PADC, new { #class = "checkbox", #id = "chbxPADC" })
</div>
<br />
<div>
Patch Anti-douleur Pied #Html.CheckBoxFor(s => s.PADP, new { #class = "checkbox", #id = "chbxPADP" })
</div>
<br />
</fieldset>
This is the JQuery part -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$("#ClickMe").click(function () {
var chk = $('#chbxPADC').is(':checked');
var chk1 = $('#chbxPADP').is(':checked');
var o = new Object();
o.PADP = chk1;
o.PADC = chk;
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(o),
success: function (data) { alert(data.PADP); },
failure: function (errMsg) { alert(errMsg); }
});
});
});
</script>
Click me
And when you click the button, it will hit following controller -
public JsonResult GetJson(SuggestionViewModel svm)
{
return Json(svm, JsonRequestBehavior.AllowGet);
}
And when you inspect the parameter using breakpoint, you will have parameters passed -
And as the response, you will have following output -
You can't post complex objects as parameter.
If you want to get json result, you should call an ajax request.
You should post your model in an ajax request. (you can use jquery .ajax metod), because you cant get values from controller action metod if you use location.href
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);
});