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
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
When I select Date in DateTimePicker, it's invoking public ActionResult Index(DateTime? test). It returns some items into the view, but those items do not appear on Index. It seems that this does not work, and I'm unsure why:
<h1>Items</h1>
#foreach (var item in Model)
{
<br />#item.Date
}
Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
List<Table> temp = new List<Table>();
return View(temp);
}
[HttpPost]
public ActionResult Index(DateTime? test)
{
masterEntities m = new masterEntities();
List<Table> temp = m.Table.Where(key => key.Date == test).Select(key => key).ToList();
return View(temp);
}
}
Index.cshtml:
#model IEnumerable<DatePicker.Models.Table>
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-2.2.0.min.js"></script>
<script src="~/Scripts/moment.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$('#datetimepicker1').datetimepicker({ useCurrent: false });
$('#datetimepicker1').on("dp.hide", function (e) {
//var temp = $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm')
$.ajax({
url: "/Home/Index",
type: "POST",
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
//data: {test: temp },
});
});
</script>
</div>
</div>
<h1>Items</h1>
#foreach (var item in Model)
{
<br />#item.Date
}
First you send an empty list to the view:
List<Table> temp = new List<Table>();
return View(temp);
So the loop doesn't show anything because, well, there's nothing to show. It's an empty list.
Then you make an AJAX request to get items:
$.ajax({
url: "/Home/Index",
type: "POST",
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
//data: {test: temp },
});
But you don't do anything with those items. You basically ignore the response from the AJAX request.
So... The data doesn't display because you haven't written any code to display the data. The AJAX request should have some sort of callback function to do something with the returned response:
$.ajax({
url: "/Home/Index",
type: "POST",
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
//data: {test: temp },
success: function (data) {
// do something with the response here
}
});
What you do with the response is up to you. Is it JSON? HTML? Based on the server-side code, it looks like it's HTML. So you can maybe put it into an element on the page. Something like this, perhaps:
$('#someElement').html(data);
That's just one example, and would of course require an element of some sort that you can identify to hold the response. You could do a lot of other things with the response.
One thing to note, however, is that your response appears to be an entire page. It includes script tags, link tags for CSS, and all sorts of markup that you otherwise already have on the client. So putting the entire page into an element isn't going to work right.
You might want to return just a partial view for this AJAX response. Or, otherwise, instead of using AJAX at all just navigate to the action to get that entire page.
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);
});
Context:
Hello, I'm developing an on line application of Tennis Club Management... I would like to create an "Available Tennis Court Interface" that allows the user to check if a court is busy or free... So in my Interface I have one DatePicker, an image "Google Maps" of the Tennis Club and 13 labels that represents all tennis courts. So in this interface, if a tennis court is busy, I would like to "color" the label in red and if the tennis court is free, in green...
Here my Interface:
Code
For that, I'm using Jquery, JavaScript and Json... Here what I have tried to make in my View :
<script type="text/javascript">
function loadCourts() {
var maDate = $('#datePicker').val();
$.post({
type: 'POST',
url: ({source:'#Url.Action("GetTennisCourt", "AvailableCourt")'}),
data: "{ 'date' : " + maDate + " }",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
timeout: 8000,
success: function(data) {
alert('test');
//How to use data and verify if a tennis is free or not ?
},
error: function(x, t, m) {
if (t === "timeout") {
window.HandleTimeout();
} else {
alert(t);
}
}
});
}
</script>
<h2>Emplacement(s) disponible(s)</h2>
<input id="datePicker" type= "text"/>
<script type="text/javascript">
$(document).ready(function () {
$('#datePicker').datetimepicker();
$('#datePicker').change(chargerCourts());
});
</script>
//Here the label
<div class="AvailableCourt">
<div class="label1" align="center">
#Html.Label("1")
</div>
<div class="label2" align="center">
#Html.Label("2")
</div>
<div class="label2" align="center">
#Html.Label("3")
</div>
<div class="label2" align="center">
#Html.Label("4")
</div>
<div class="label3" align="center">
#Html.Label("5")
</div>
<div class="label4" align="center">
#Html.Label("6")
</div>
<div class="label5" align="center">
#Html.Label("7")
</div>
<div class="label6" align="center">
#Html.Label("8")
</div>
<div class="label7" align="center">
#Html.Label("9")
</div>
<div class="label8" align="center">
#Html.Label("10")
</div>
<div class="label9" align="center">
#Html.Label("11")
</div>
<div class="label10" align="center">
#Html.Label("12")
</div>
<div class="label11" align="center">
#Html.Label("13")
</div>
}
</div>
Controller method
//Get all the tennis courts and verify if a court is busy or not (Available attribute)
public JsonResult GetTennisCourt(DateTime date)
{
System.Diagnostics.Debug.WriteLine("test");
var reservations = db.Reservations.Include(c => c.Customer);
foreach (var reservation in reservations)
{
//Verify that a court is available or not
if (reservation.Date ==date)
{
if (date.Hour > reservation.FinishTime.Hour || date.Hour < reservation.StartTime.Hour)
{
var id = reservation.TennisCourtID;
TennisCourt tennisCourt = (TennisCourt) db.TennisCourts.Where(t => t.ID == id);
tennisCourt.Available = true;
db.Entry(tennisCourt).State = EntityState.Modified;
db.SaveChanges();
}
else
{
var id = reservation.TennisCourtID;
TennisCourt tennisCourt = (TennisCourt) db.TennisCourts.Where(s => s.ID == id);
tennisCourt.Available = false;
db.Entry(tennisCourt).State = EntityState.Modified;
db.SaveChanges();
break;
}
}
}
var courts = from c in db.TennisCourts
select c;
courts = courts.OrderBy(c => c.ID);
System.Diagnostics.Debug.WriteLine("test");
return Json(courts, JsonRequestBehavior.AllowGet );
}
When I'm using Firebug, I get an error in my function "loadCourts" and so my controller's method (getTennisCourts) is never reaches) I don't understand why:
Questions
So, my questions are :
1) Why get I an error in Firebug ?
2) Why is my Controller's method never reaches ?
3) How could I use "data" in my function "loadCourts" to check if a tennis court is free or not ?
Sorry for the length and thanks in advance...
For Darin Dimitrov :
Try like this:
// get the underlying Date object from the datepicker instead
// of using .val()
var maDate = $('#datePicker').datepicker('getDate');
$.ajax({
type: 'POST',
url: '#Url.Action("GetTennisCourt", "AvailableCourt")',
data: '{ "date":"\\/Date(' + maDate.getTime() + ')\\/" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
timeout: 8000,
success: function(data) {
// we loop through the collection of courts
// returned by the server and we can access each
// element's properties
$.each(data, function(index, court) {
alert(court.ID);
});
},
error: function(x, t, m) {
if (t === 'timeout') {
window.HandleTimeout();
} else {
alert(t);
}
}
});
Notice that I used $.ajax instead of $.post. And I have used the datepicker's getDate method to fetch the native Date object and encode it.
I dont know C# but this line:
url: ({source:'#Url.Action("GetTennisCourt", "AvailableCourt")'}),
Is resolving the url as an object, if you had
url : '/path/to/controller'
It might work
The 'data' in the success function is JSON so you can treat it as an object.
data.xyz