I have created class method in call GetDatabase() with following code:
public string GetDatabase()
{
var db_holiday = dbObj.RetrieveData("SELECT Holiday_description, Date FROM ServiceReport.dbo.WS_Holidays");
if (db_holiday != null)
{
var holiday_rows = db_holiday.Tables[0].Rows;
List<string> des_holiday = new List<string>();
List<string> des_date = new List<string>();
foreach (DataRow row in holiday_rows)
{
var holiday = row["Holiday_description"].ToString();
var date = row["Date"].ToString();
des_holiday.Add(holiday);
des_date.Add(date);
}
}
I've stored two databases into separated list which is des_holday and des_date.
In ASP.net:
<div class="container col-lg-2 bg-warning ">
<div ID="week_display" class="m-grid-col-center">
</div>
</div>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "Test.aspx/GetDatabase",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess
});
});
</script>
</head>
I'm currently using .ajax() to call back GetDatabase().
My main goal is to display all of my element inside the two list.
I'm stuck right and don't know what to do.
I solved it. When the ajax is running, the success will run the OnSuccess function. By putting
function OnSuccess(data) {
console.log(data.d);
}
Will obtain the data.
Related
I'm having some issues with updating a partial view in my index view. Basically, based on a click, I would like to have updated information.
//controller
public ActionResult Index()
{
var filteredObservations = getFilteredObservationSessions().ToList();
var observationManagementVm = new ObservationManagementVM(filteredObservations);
return View(observationManagementVm);
}
public ActionResult indexPagedSummaries(int? page, List<ObservationSessionModel> data)
{
var alreadyFilteredObservations = data;
int PageSize = 10;
int PageNumber = (page ?? 1);
return PartialView(alreadyFilteredObservations.ToPagedList(PageNumber, PageSize));
}
My main view
//index.cshtml
#model AF.Web.ViewModels.ObservationManagementVM
....
<div id="testsim">
#Html.Action("indexPagedSummaries", new { data = Model.ObservationSessions })
</div>
<input id="new-view" value="Sessions" type="button" />
<script>
$("#new-view").click(function() {
$.ajax({
type: "GET",
data: { data: "#Model.FeedBackSessions" },
url: '#Url.Action("indexPagedSummaries")',
cache: false,
async: true,
success: function (result) {
console.log(result);
$('#testsim').html(result);
$('#testsim').show();
}
});
});
</script>
....
And my partial view
//indexPagedSummaries.cshtml
#model PagedList.IPagedList<AF.Services.Observations.ObservationSessionModel>
#using (Html.BeginForm("indexPagedSummaries"))
{
<ol class="vList vList_md js-filterItems">
#foreach (var item in Model)
{
#Html.DisplayFor(modelItem => item)
}
</ol>
<div>
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page }))
</div>
}
Html.Action() returns what I want perfectly, but it doesn't seem to be able to be triggered by a button click.
So, I'm not getting any errors, but the url doesn't give any data back. When I try to run the Observation/indexPagedSummary url without passing in data, I get a System.ArgumentNullException error, so I'm assuming that something is being transferred to the view model. Any help would be so appreciated.
Have not run your code but I believe it is because you are not sending the data along with the #Url.Action
Main View:
//index.cshtml
#model AF.Web.ViewModels.ObservationManagementVM
....
<div id="testsim">
#Html.Action("indexPagedSummaries", new { data = Model.ObservationSessions })
</div>
<input id="new-view" value="Sessions" type="button" />
<script>
$("#new-view").click(function() {
$.ajax({
type: "GET",
data: { data: "#Model.FeedBackSessions" },
url: '#Url.Action("indexPagedSummaries", "[Controller Name]", new { data = Model.ObservationSessions})',
cache: false,
async: true,
success: function (result) {
console.log(result);
$('#testsim').html(result);
$('#testsim').show();
}
});
});
</script>
If that doesn't help I have had issues when I have had a content-type mismatch or a datatype mismatch. You may need to add those to you ajax request.
Change your ajax data line to this:
data: { data: JSON.stringify(#Model.FeedBackSessions) },
You may also need to add these lines to the ajax:
dataType: 'json',
contentType: 'application/json; charset=utf-8',
You can see in one of your comments above that the current URL is being formed with a description of the List Object, rather than the contents of it:
http://localhost:60985/Observation/indexPagedSummaries?data=System.Collections.Generic.List%601%5BAF.Services.Observations.ObservationSessionModel%5D&data=System.Collections.Generic.List%601%5BAF.Services.Observations.ObservationSessionModel%5D&_=1482453264080
I'm not sure if there's a better way, but you may even have to manually get the model data into Javascript before posting it.
eg:
<script>
var temp = [];
#foreach (var item in Model.FeedBackSessions){
#:temp.push(#item);
}
</script>
and then data: { data: JSON.stringify(temp) },
I want to show Course Code after selecting a department from drop down.
it searches from database and get but does not show at browser. Here is the drop down:
<select name="Id" id="Id">
<option value="">Select Department</option>
#foreach (var departments in ViewBag.ShowDepartments)
{
<option value="#departments.Id">#departments.Name</option>
}
</select>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script>
$(document).ready(function() {
$("#Id").change(function() {
var departmentId = $("#Id").val();
var json = { departmentId: departmentId };
$.ajax({
type: "POST",
url: '#Url.Action("ViewAllScheduleByDept", "ClassSchedule")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function (data) {
//$("#myTable").append('<tr><th>ID</th><th>Name</th></tr>');
$('#Code').val(data.Code);
//$('#ContactNo').val(data.ContactNo);
//$('#Type').val(data.Type);
}
});
});
});
</script>
I am using mvc.
Your code should work fine as long as ViewAllScheduleByDept action method returns a json structure with a Code property.
[HttpPost]
public ActionResult ViewAllScheduleByDept(int departmentId)
{
//values hardcoded for demo. you may replace it value from db table(s)
return Json( new { Code="HardcodedValue", ContactNo="12345"} );
}
and you have an input form element with Id property value as Code in your page
<input type="text" id="Code" />
and you do not have any other script errors which is preventing your js code to execute.
Also, since you are sending just the Id value, you don't really need to use JSON.stringify method and no need to specify contentType property value.
$("#Id").change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("ViewAllScheduleByDept", "ClassSchedule")',
data: { departmentId: $("#Id").val() },
success: function (data) {
alert(data.Code);
$('#Code').val(data.Code);
}
,error:function(a, b, c) {
alert("Error" + c);
}
});
});
use last before append
$("#myTable").last().append("<tr><td>ID</td></tr><tr><td>Name</td></tr>");
please see the link for details
Add table row in jQuery
I'm new to AJAX, and I don't understand, why my data was not sent to controller.
So, on my View I have two input forms and a button:
HTML:
<input type="text" name="AddName">
<input type="text" name="AddEmail">
<button class="btn btn-mini btn-primary" type="button" name="add_btn" onclick="DbAdd()">Add</button>
I need after button "add_btn" clicked take data from these two inputs and send them to controller.
JavaScript:
<script type="text/javascript">
function DbAdd()
{
// Get some values from elements on the page:
var $form = $(this),
addedName = $form.find("input[name='AddName']").val(),
addedEmail = $form.find("input[name='AddEmail']").val();
$("#UserTable").html("<div>Please Wait...</div>");
$.ajax(
{
type: "POST",
url: "Save",
data:
{
name: addedName, email: addedEmail,
},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnError
});
}
And this is my controller's method "Save" (I need to save data got from ajax to my DB):
[HttpPost]
public ActionResult Save(User userinfo)
{
string message = "";
using (var uc = new UserContext())
{
uc.UserList.Add(userinfo);
uc.SaveChanges();
message = "Successfully Saved!";
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = message };
}
else
{
ViewBag.Message = message;
return View(userinfo);
}
}
The problem is that when I put a break point to my controller's method, I don't receive data from ajax, null's only. So I add an empty record to DB.
Any suggestions?
Looks like $form.find("input[name='AddName']").val() and $form.find("input[name='AddEmail']").val() both return null. You should use $("input[name='AddName']").val() and $("input[name='AddEmail']").val() instead. Change the definition of DbAdd() to below
<script type="text/javascript">
function DbAdd()
{
// Get some values from elements on the page:
var addedName = $("input[name='AddName']").val(),
addedEmail = $("input[name='AddEmail']").val();
var user = { Name: addedName, Email: addedEmail };
$("#UserTable").html("<div>Please Wait...</div>");
$.ajax(
{
type: "POST",
url: "Save",
data: JSON.stringify({ userinfo: user }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnError
});
}
</script>
There is an extra comma which may be causing syntax error:
data:
{
name: addedName, email: addedEmail, //<------------ here
}
and pass data like this:
var userinfo = { name: addedName, email: addedEmail };
data: JSON.stringify(userinfo)
Also you should see : Posting JavaScript objects with Ajax and ASP.NET MVC
//When focusout event is working, tested with alert.. but ajax call is not working and my aspx.cs method also not firing.. Please solve this issue.
//This is my aspx page jquery code.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var elem = document.getElementById('<%=txtProduct.ClientID %>');
$(elem).focusout(function () {
myF($(this).val());
});
function myF(value) {
var fist = value.split(' ( ', 1);
$.ajax({
type: 'POST',
url: 'Invoice.aspx/getProductDetails',
data: "{'strCode':'" + fist + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert(response.d.toString());
},
failure: function (response) {
alert('error');
}
});
}
});
</script>
//Server side code
[WebMethod]
public static string getProductDetails(string strCode)
{
List<string> companyInfo = new List<string>();
companyInfo.Add(HttpContext.Current.Cache[Convert.ToString(HttpContext.Current.Session["UserID"]) + "CompanyID"].ToString());
companyInfo.Add(strCode);
List<string> price = Database.MasterDB.getProductInfo(companyInfo);
if (price.Count > 0)
return price[0].ToString();
else
return "000";
}
Since you are using Session thing inside web method, that might be giving null values or blank values. This is because you have not enabled session for webmethod.
Like this - [WebMethod(EnableSession=true)].
Read more
I am trying to
1) create a JQuery AutoComplete box that is populated from an aspx method, and
2)once I get the results, I wish to populate these results inside a list.
At the moment I am trying to do step one however without my success.
My code is as follows:-
ASPX
<script>
$(function () {
$("#persons").autocomplete({
//source: availableTags
source: function (request, response) {
var term = request.term;
var personArray = new Array();
$.post('JQAutoComplete.aspx/FetchPersonList', { personName: term }, function (persons) {
personArray = persons;
alert('PersonArray' - personArray);
alert('Persons' - persons);
response(personArray);
});
}
});
});
<div class="ui-widget">
<label for="persons">Persons: </label>
<input id="persons" />
</div>
</body>
and my aspx.cs is as follows :-
public JsonResult FetchPersonList(string personName)
{
var persons = ctx.GetDataFromXML(false, 0);
return (persons) as JsonResult;
}
*************UPDATE ASPX.CS*******************
ok so I changed the method to this:-
[WebMethod]
public static List<Person> FetchPersonList()
{
//var persons = this.HouseService.SelectByName(houseName).Select(e => new String(e.Name.ToCharArray())).ToArray();
var persons = ctx.GetDataFromXML(false, 0);
return (List<Person>) persons;
}
but I am still not getting through the method!
However the code is not hitting this method at all.
How can I get this list?
Thanks for your help and time
Ok I found the problem.
I changed my JQuery to the following and its calling the method now :-
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#persons").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "JQAutoComplete2.aspx/FetchPersons",
data: "{'name':'" + document.getElementById('persons').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
alert(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
and my ASPX.CS looks like this :-
[WebMethod]
public static List<Person> FetchPersons(string name)
{
var persons = ctx.GetDataFromXML(false, 0);
return (List<Person>)persons;
}