I know this question has been asked many times but no matter what i try i just can't get it to work. I have an actionResult that accepts three parameters and returns a partial view. Now what i want to do is take the values of three elements and re-render the view in a div using them. I have tried to use the captured data to render the div succesfully but i can't figure out what i'm doing wrong with jquery
In the script file are included the last things i tried(although in every attempt there was some tweaking before giving up)
Here is the RenderAction in the main view (that works)
<div id="tables">
#{ Html.RenderAction("_Tables", new { date = "5/10/2019", time = "13:00", seats = "1" });}
</div>
the action result that returns said Partial
public ActionResult _Tables(string date, string time, int seats)
{
return PartialView("_Tables", checkTables(date,time,seats));
}
And finally the script(searchTable is a button near the fields. Their values are captured succesfully but load does not work)
$('#searchTable').click(function () {
var date = document.getElementById("datepicker").value;
var time = document.getElementById("time").value;
var seats = document.getElementById("seats").value;
alert(date);
//var data = JSON.stringify({
// 'date': date,
// 'time': time,
// 'seats': seats
//});
//$.ajax({
// type: "POST",
// url: '/Home/_Table/',
// data: data,
// dataType: "html",
// success: function (result) { success(result); }
//});
//function success(result) {
// alert(result);
// $("#tables").html(result);
// $("#tables").load("#tables")
//};
//$.ajax({
// url: "/Home/_Table",
// type: "GET",
// contentType: "application/json; charset=utf-8",
// data: data,
// success: function (data) {
// $('#target').html(data); // loading partialView into div
// }
//});
//$('#tables').load('#{ Html.RenderAction("_Tables", new { date = "' + date + '", time = "' + time + '", seats = "' + seats + '" });}');
$('#tables').load('#Url.Action("_Tables","Home")', { 'date': date, 'time': time, 'seats': seats });
alert(time);
//alert('#{ Html.RenderAction("_Tables", new { date = "' + date + '", time = "' + time + '", seats = "' + seats + '" });}');
});
I know the problem lies in my lack of understanding but i do not have the time to research ajax. My internship is based on "figuring it out" under deadlines"
Suppose you have a div with id tables as
<div id="tables">
You can use the following method of appending the partial view content based on your paramters as
$.ajax({
url: "/Home/_Tables?date=" + val + "&time="+ val +"&seats="+seats,
type: "POST",
cache: false,
success: function (result) {
$("#tables").empty();
$("#tables").html(result);
},
error: function () {
$("#tables").empty();
}
});
this will be the main view ajax function.and in the controller do the following
public ActionResult _Tables(string date, string time,string seats)
{
// here you can provide model,any viewbag values etc to the partial view and you will get corresponding html result
return PartialView("Yourpartial ViewName");
}
I see a commented line in your code :
$("#tables").html(result);
It's all you need!
You should fill your div with all partial view html that returns from your controller.
Related
A partial view (_AddItem.cshtml) is called from the main view (Category.cshtml) in order to add existing items to the page on load.
I'm now adding AJAX so that an item can be added, to the page, by the user at the click of a button. When the form is subsequently submitted the item will be added to the model.
The partial view relies on the category model (activeCategoryModel) and two variables. Currently, these are successfully being passed from the view in the following way:
Category.cshtml
#Html.Partial(
"_AddItem",
activeCategoryModel,
new ViewDataDictionary(ViewData) { { "itemIndex", itemIndex }, { "itemLabel", itemLabel } }
);
My question is how can I pass the model (activeCategory) and these two variables when using AJAX? Below is the code I've started writing for the AJAX post:
Button and inputs added to view (Category.cshtml)
<input id="add-item-label" type="text" />
<input id="nextItemIndex" type="hidden" value="#activeCategoryModel.Items.Count" />
<button id="add-item" type="button">Add Item</button>
AJAX post added in javascript
This is not necessary fully functional code, I've just attempted to write an AJAX post with the variables in the 'data' parameter.
$("#add-item").click(function () {
var itemIndex = $("#nextItemIndex").val();
var itemLabel = $("#add-item-label").val();
$.ajax({
type: "POST",
url: '#Url.Action("_AddItem")',
data: '{{itemIndex: ' + itemIndex + '}, {itemLabel: ' + itemLabel + '}}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
$("#nextItemIndex").val($("#nextItemIndex").val() + 1);
},
error: function () {
alert("Error while adding item");
}
});
return false;
});
Partial view call added to Controller
I think this is where the model and variables need to be included in the partial view call.
public ActionResult _AddItem(string itemIndex, string itemLabel)
{
return PartialView();
}
Partial View (_AddItem.cshtml)
This has not been changed for the AJAX post.
#model CategoryModel
#{ int i = (int)ViewData["itemIndex"];}
#{ string l = (string)ViewData["itemLabel"];}
...
There are different ways in this case,
Example : Html.RenderPartial directly rendered partial action without ajax.
If you want to use Ajax to call partialView , you must be render
Html. Because PartialView returned Html.
I think the most important value in Ajax request is dataType and
the second important point is added returned html data in a div element
jQuery("#add-item").click(function () {
var dItemIndex = 1; //$("#nextItemIndex").val();
var dItemLabel = "Text"; // $("#add-item-label").val();
$.ajax({
type: "POST",
url: '#Url.Action("_AddItem","Home")',
data: { itemIndex: dItemIndex, itemLabel: dItemLabel },
dataType: "html",
//contentType: "application/json; charset=utf-8",
success: function (d) {
console.log("Success");
$("#partialData").html(d);
**// Create div in cshtml Page
// <div id="partialData"></div>**
},
error: function () {
alert("Error while adding item");
}
});
return false;
});
At the controller side you can read parameters and fill in the content and send the PartialView as follows.
public ActionResult _AddItem(string itemIndex, string itemLabel)
{
ViewData["itemIndex"] = itemIndex;
ViewData["itemLabel"] = itemLabel;
return PartialView(new CategoryModel { Id = 5, Text = "Sample 5" });
}
I am trying to add the record to DB using Ajax and get the data back from JsonResult if success, in order to call the function further, but somehow always land in the error: parseerror. However, the record is inserted in DB.
Here is my post method:
$("body").on("click", "#btnAdd", function () {
var txtTermName = $("#txtTermsName");
var txtAlternativeTerms = $("#txtAlternativeTerms");
$.ajax({
type: "POST",
url: "/Administration/AddTerm",
data: '{name: "' + txtTermName.val() + '", alternatives: "' + txtAlternativeTerms.val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var row = $("#tblTerms tr:last-child");
if ($("#tblTerms tr:last-child span").eq(0).html() != " ") {
row = row.clone();
}
AppendRow(row, r.Name, r.Alternatives);
txtTermName.val("");
txtAlternativeTerms.val("");
},
error: function(textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
});
And my controller JsonResult:
[HttpPost]
public JsonResult AddTerm(Term term)
{
this.SaveTerm(term);
return Json(term);
}
Any comment or suggestion is appreciated
UPDATE
Json(term).Data contents:
- Json(term).Data {Models.Term} object {Models.Term}
+ ChangedBy
Description null string
ID 27 int
Inactive false bool
Name "sdfgdsgf" string
SynonymsList "sdfgdsgfdsgsdgf" string
+ Updated {09.08.2018 10:00:50} System.DateTime
Looks like an exception is being called somewhere after your database save call (I take it the SaveTerm method does more than just save the item?) resulting in an error page being returned instead of JSON - hence the parse error.
Try adding a Try { } Catch { } to the action and I reckon there will be an exception caught from the SaveTerm method.
I am having gridview showing data from database such as
ProductID ProductName Price
----------------------------------
A00001 Apple 10.00 ADDTOCART
The ADDTOCART is a button.
GridViewRow gr = ((sender as LinkButton).NamingContainer as GridViewRow);
string itemId = gr.Cells[0].Text.Trim();
These are the code I use for codebehind to get the ProductID when click on ADDTOCART
Need assist for the code which can let the variable I declared in Jquery to get the ProductID like what the codebehind do when I click the ADDTOCART button.
function ShowCurrentTime() {
var name = "The name";//$("#<%=txtUserName.ClientID%>")[0].value; //get the data.
var id = "The id";//$("#<%=TextBox1.ClientID%>")[0].value; //get the data.
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetCurrentTime", //the url and method name of the webmethod
data: "{ name: '" + name + "', id: '" + id + "' }", //pass in 2 data.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) { //fixed
alert(response.d);
}
});
}
function OnSuccess(response) { //fetching object come out, object inside got name and id, need to specific which data you want by obj.id/obj.name
var obj = response.d; //fetching the webmethod
alert(obj.id + "" + obj.name) //display the return
$('#trycart').append("<li>" + obj.id + "</li>");
$('#cart').append("<tr><td>" + obj.id + "</td><td>" + obj.name +"</td></tr>"); //access the table id=cart, add in the data comeback from webmethod.
}
I need assist to have the var name to have the product name, and var id to have the id when I click ADDTOCART.
The element name and selectors can be manipulated by looking at the Dom.
In the button onclick pass this as parameter
function ShowCurrentTime(element)
{
var name = $(element).closest("tr").find("input[id*='txtUserName']").val();
var id = $(element).closest("tr").find("input[id*='TextBox1']").val();
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetCurrentTime", //the url and method name of the webmethod
data: "{ name: '" + name + "', id: '" + id + "' }", //pass in 2 data.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) { //fixed
alert(response.d);
}
});
}
I guess that Your data from database is in your C# application, which is on your server side. The code above are jquery/javascript, which is on your client side.
It's very important to know the difference on server side and client side. Basically say, everything you can see from "view source" from browser, are client side, otherwise, on server side.
So go back to your question, you can build html with data from database in your c# application, or build json data object, and in turn use it in jquery.
Hope helps
I am trying to create Multilevel Dropdown.
I have default dropdown with values
Ex. Parent Dropdown with Id='ddl1'
If we select value from it then load data from server with selected and Create new dropdown name as child dropdown, and again select value from child and load data from server, if data present then create child dropdown.
we have to create drowpdown, till n level.
'Ex. i am creating like below'
function createdropdown(id) {
var labelHtml = "<tr id='trFormType" + id + "' class='trFormType'><td><label class='tdLabel'>" + labelFormType + " * </label></td>";
labelHtml += "<td><select class='ddlFormType' id='ddlFormType" + id + "' name='ddlFormType" + id + "' >";
labelHtml += "<option value=''";
labelHtml += ">" + labelSelect + "</option>";
labelHtml += "</select></td></tr>";
return labelHtml;
}
var selectedId=''; $(".ddlFormType").live("click", function () { selectedId= "#" + $(this).prop('id'); });
$(selectedId).live("change", function () { $.ajax({ url: Url + 'Method/' + (selectedId).val(), type: 'GET', dataType: 'json', cache: false, timeout: 9000, success: function (data) { $("#detailTable tbody").append(createdropdown(currentId)); }
});
'But .change event not get fired, for dyncamically created dropdown'
'Hope you can understand?'
For creating n level dropdowns you need to create a dropdown in ajax callback like this:
$.ajax({
url: "Your URL",
method: "GET",
dataType: 'json',
success: function (data) {
$("Your Dropdown Conatiner").append("<select><option name="option1" value="1"></option>...</select>");
},
error: function (data) {
}
});
It think your problem is that you are creating the select after the DOM has been fully loaded and jQuery has already registered all events.
If you want to add dinamically N selects you should include a call to register it inside the code you are adding to the DOM, check this sample:
<div id="select-container"></div>
<script>
function CreateSelect(id){
return `<select id="ddl` + id + `">
<option value="Opcion">Opcion<\/option>
<option value="Opcion2">Opcion 2<\/option>
<\/select>
<script>
RegisterSelectChangeEvent(` + id + `);
<\/script>`;
}
function RegisterSelectChangeEvent(id){
console.log("Event Raised");
$("#ddl" + id).on("change", function (e) {
jQuery("#select-container").append(CreateSelect(id+1));
});
}
(function(){
jQuery("#select-container").append(CreateSelect(1));
})();
</script>
You can see it working here:
https://codepen.io/anon/pen/LQRqYY
I'm developing an online application of tennis club management... (MVC 3, Entity Framework Code first,...)
I've an Interface that allows the user to consult the available tennis court :
In my "AvailableCourtController", I've a function which return the tennis courts :
[HttpPost]
public JsonResult GetTennisCourt(DateTime date)
{
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);
return Json(courts, JsonRequestBehavior.AllowGet );
}
So, I would like to change the color of my label if the tennis court is busy or free... For that I use "Ajax":
"View" (What I've tried to make)
<input id="datePicker" type= "text" onchange="loadCourts"/>
<script type="text/javascript">
$('#datePicker').datetimepicker();
</script>
<script type="text/javascript">
function loadCourts() {
var myDate = $('#datePicker').value();
$.ajax({
url: ("/AvailableCourt/GetTennisCourt?date=myDate "),
success: function (data) {
alert('test');
//change label's color
}
});
}
</script>
I never get the message "test"... So I have make something wrong with my Ajax function or my controller's method... My goal is to get the tennis court, check if they're free or not and change color in red if busy, and in green if free...
Can you help me to find what I'm doing wrong please? Sorry :( But I'm a beginner with Ajax...
This line is not passing a date in the querystring:
url: ("/AvailableCourt/GetTennisCourt?date=myDate "),
should be:
url: ("/AvailableCourt/GetTennisCourt?date=" + myDate),
EDIT: Also you're not getting the value correctly:
var myDate = $('#datePicker').value();
should be:
var myDate = $('#datePicker').val();
Your datetimepicker() call has to occur inside of a document.ready. Here is the corrected code:
<input id="datePicker" type= "text"/>
<script type="text/javascript">
$(document).ready(function () {
$('#datePicker').datetimepicker();
$('#datePicker').change(loadCourts);
});
function loadCourts() {
var myDate = $('#datePicker').val();
$.post({
data: "{ 'date' : " + myDate + " }",
url: (#Url.Action("AvailableCourt", "GetTennisCourt"),
success: function (data) {
alert('test');
//change label's color
}
});
}
</script>
}
Your url is wrong :-)
Should be:
$.ajax({
url: "/AvailableCourt/GetTennisCourt?date="+myDate, // without ( )
success: function (data) {
alert('test');
//change label's color
}
});
A more verbose AJAX call:
$.ajax({
type: 'POST',
data: "{ 'date' : " + myDate + " }",
url: '/AvailableCourt/GetTennisCourt',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
timeout: 8000, // 8 second timeout
success: function (msg) {
},
error: function (x, t, m) {
if (t === "timeout") {
HandleTimeout();
} else {
alert(t);
}
}
});
I agree with #CAbbott that your URL was not created correctly. But with date values (and multiple query string values in general), you may be better off adding your date parameter in a data object literal in your ajax call:
function loadCourts() {
var myDate = $('#datePicker').val();
$.ajax({
url: ("/AvailableCourt/GetTennisCourt"),
data: { date: myDate },
success: function (data) {
alert('test');
//change label's color
}
});
}
jQuery will append your data onto the querystring for you and format it appropriately.
From the jQuery API docs:
The data option can contain either a query string of the form
key1=value1&key2=value2, or a map of the form {key1: 'value1', key2:
'value2'}. If the latter form is used, the data is converted into a
query string using jQuery.param() before it is sent.