Data coming in ajax code not getting displayed - asp.net

I have li tags that includes links to different pages. Now i am trying to create a searcj by clicking on specific li tag. I want when user clicks on this li named 'Field Workers', a sub li appears that includes names of all field workers that are in the database. Ajax code is used to diaplay the field workers. I am getting data in the ajax cide but somehow it is not getting displayed. Can anyone help me with this?
Ajax code:
<script>
var ajaxOptions = {
type: "POST", url: null, success: null, async: true,
data: "", dataType: "json", contentType: "application/json; charset=utf-8"
}
$(function () {
BindFW();
})
function BindFW() {
ajaxOptions.data = "";
ajaxOptions.url = "WebForm1.aspx/BindFieldWorkers"
ajaxOptions.success = function (result) {
if (result.d != null && result.d != "") {
//$("#templateFW").tmpl(result.d).appendTo("#ulFW");
$.each(result.d, function () {
$('#ulFW').append();
});
}
}
$.ajax(ajaxOptions);
}
</script>
<ul>
<li class="has-sub">
<a href="javascript:;">
<i class="icon-search"></i>
<span class="title">Field Worker Name</span>
<span class="arrow "></span>
</a>
<ul id="ulFW" class="sub">
</ul>
</li>
</ul>

use from this script:
$(document).ready(function () {
BindFW(10);
});
function BindFW(StateId) {
var data = {
StateId: StateId
};
$.ajax({
type: 'POST',
url: './WebForm1.aspx/BindFieldWorkers',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(data),
success: function (data) {
if (!data.d['Result']) {
alert('no records found!');
return;
}
var records = data.d['Records'];
for (var i = 0; i < records.length; i++) {
$('#ulFW').append(function () {
return $('<li>').text(records[i].Text).attr('data-id', records[i].ID)
});
}
},
error: function (data) {
alert('failed to connect to server!');
}
});
}
and this in your code behind:
[System.Web.Services.WebMethod]
public static object BindFieldWorkers(int StateId)
{
try
{
List<object> result = new List<object>();
for (int i = 0; i < 10; i++)
{
result.Add(new
{
ID = i,
Text = "Text " + i
});
}
return new { Result = true, Records = result };
}
catch (Exception ex)
{
return new { Result = false, Message = ex.Message };
}
}

Related

DotNetNuke mvc fill in form items on SelectList change

I am trying to populate form items based on a dropdown selection without refreshing the entire page or loading a new view. This was fairly simple in web forms using an UpdatePanel, for instance. However, I can't get this to work in MVC.
I've tried many of the solutions I could find. I don't know if this is a DotNetNuke issue.
Debugging shows the controller firing and retrieving a record but the form items are never populated.
I've tried both a jquery.post and an .ajax call. Neither work.
View:
#inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage<IMS.Model.lh.Associations>
#using IMT.LH.AssociationAdmin.Models
#using IMS.Model.lh
#{
ViewBag.Title = "Association";
}
<h2>Association</h2>
<div id="Associations-#Dnn.ModuleContext.ModuleId">
#Html.DropDownList("SelectAssociation")
</div>
<div id="Association-#Dnn.ModuleContext.ModuleId">'
#Html.LabelFor(m=>m.AssociationID)<br />
#Html.Label("Title")<br />
#Html.Label("Slug")<br />
#Html.Label("Description")<br />
#Html.Label("Tagline")<br/>
</div>
<script type="text/javascript">
const rvtoken = $("input[name='__RequestVerificationToken']").val();
const moduleId = #Dnn.ModuleContext.ModuleId;
const tabId = #Dnn.ModuleContext.TabId;
$.ajaxSetup({
headers: {
"RequestVerificationToken": rvtoken
}
});
$('#SelectAssociation').change(
function() {
$.post(
"/DesktopModules/MVC/LH.AssociationAdmin/Association/SelectAssociation",
{
id: $(this).val()
}),
function() {
alert("success");
}
/*$.ajax({
url: "/DesktopModules/MVC/LH.AssociationAdmin/Association/SelectAssociation",
method: "Post",
data: {
id: $(this).val()
},
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken
},
success: function() {
alert("success");
},
fail: function() {
alert("fail");
}
});
*/
});
</script>
Controller:
[HttpPost]
[DotNetNuke.Web.Mvc.Framework.ActionFilters.ValidateAntiForgeryToken]
public ActionResult SelectAssociation()
{
ModelState.Clear();
int id = Convert.ToInt32(Request.Form["id"]);
using (var ac = new AssociationsController())
{
ac.GetById(id);
return PartialView("Index", ac.CurrentRec);
}
}
Ok. One way I've found is to simply return a json object to the .ajax call and parse it:
$.ajax({
cache: false,
dataType: 'json',
url: "/DesktopModules/MVC/LH.AssociationAdmin/Association/SelectAssociation",
method: "Post",
data: {
id: $(this).val()
},
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken
},
success: function(data) {
//alert(data.AssociationID);
$('#AssociationID').text(data.AssociationID);
$('#Title').text(data.Title);
$('#Slug').text(data.Slug);
$('#Description').text(data.Description);
$('#Tagline').text(data.Tagline);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
console.log(jqXHR);
}
});
});
Controller:
[HttpPost]
[DotNetNuke.Web.Mvc.Framework.ActionFilters.ValidateAntiForgeryToken]
public ActionResult SelectAssociation()
{
ModelState.Clear();
int id = Convert.ToInt32(Request.Form["id"]);
using (var ac = new AssociationsController())
{
ac.GetById(id);
return Json(ac.CurrentRec);
//return PartialView("Index", ac.CurrentRec);
}
}
But, I am certainly open to other suggestions.

Script not works (ASP.NET MVC)

I have script for recording video
Here is code of it
var fileName;
stop.onclick = function () {
record.disabled = false;
stop.disabled = true;
window.onbeforeunload = null; //Solve trouble with deleting video
preview.src = '';
fileName = Math.round(Math.random() * 99999999) + 99999999;
console.log(fileName);
var full_url = document.URL; // Get current url
var url_array = full_url.split('/') // Split the string into an array with / as separator
var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
I try to get url with this row var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
and with this code write to table filename
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
but it not works.
There is my Action method for it
[HttpPost]
public ActionResult LinkWriter(string link, int id) {
Link link_ = new Link
{
Link1 = link,
Interwier_Id = id,
};
db.Link.Add(link_);
db.SaveChanges();
return View();
}
But it not works. Where is my mistake?
UPDATE
As I understood not works this
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}

Why highchart not show me in asp.net?

I'm beginner in asp.net and highchart control,want to use highchart control in my web application web form,for that purpose read this tutorial:
this tutorial
and write this web service in my project:
public class cityPopulation
{
public string city_name { get; set; }
public int population { get; set; }
public string id { get; set; }
}
[WebMethod]
public List<cityPopulation> getCityPopulation(List<string> pData)
{
List<cityPopulation> p = new List<cityPopulation>();
cityPopulation cpData = new cityPopulation();
cpData.city_name = "tabriz";
cpData.population = 100;
p.Add(cpData);
return p;
}
that web service name is this:
WebService1.asmx
and in my web form write this script :
<script type="text/javascript">
function drawPieChart(seriesData) {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Population percentage city wise'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: "Brands",
colorByPoint: true,
data: seriesData
}]
});
}
$("#btnCreatePieChart").on('click', function (e) {
var pData = [];
pData[0] = $("#ddlyear").val();
var jsonData = JSON.stringify({ pData: pData });
$.ajax({
type: "POST",
url: "WebService1.asmx/getCityPopulation",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
var arr = []
$.map(aData, function (item, index) {
var i = [item.city_name, item.population];
var obj = {};
obj.name = item.city_name;
obj.y = item.population;
arr.push(obj);
});
var myJsonString = JSON.stringify(arr);
var jsonArray = JSON.parse(JSON.stringify(arr));
drawPieChart(jsonArray);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
e.preventDefault();
});
//*
</script>
before that script write this code:
<script src="Scripts/jquery-2.2.3.min.js"></script>
<script src="Scripts/Highcharts-4.0.1/js/highcharts.js"></script>
and write this html code:
<select id="ddlyear">
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
<option>2014</option>
<option>2015</option>
</select>
<button id="btnCreatePieChart">Show </button>
<br />
<div>
<div id="container" style="width: 500px; height: 500px"></div>
</div>
but when i run project and fire the button,can not see anything,and chart not show to me,what happen?is my code incorrect?how can i solve that problem?thanks.
i think ajax can not call the web service!

Autocomplete Web Service in ASP.Net web forms

I have a web service for multiple item selection, its working fine but i am getting Undefined data. anyone can tell me solution for it. I am attaching my error screenshot too with this post, please see them below.
Web Service JSON Code
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{'skill':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("No Result Found");
}
});
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#ctl00_ContentMain_TextBoxSkills").bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
</script>
Web Service:
[WebMethod]
public List<UserRegistration> GetAutoCompleteData(string skill)
{
List<UserRegistration> list = new List<UserRegistration>();
UserRegistrationHelper userRegistrationHelper = new UserRegistrationHelper();
using (DataTable dataTable = userRegistrationHelper.GetSkillsList(skill))
{
if (CommonFunctions.ValidateDataTable(dataTable))
{
foreach (DataRow dr in dataTable.Rows)
{
var SkillsList = new UserRegistration
{
SkillId = Convert.ToInt32(dr["SkillId"].ToString()),
Skills=dr["SkillName"].ToString()
};
list.Add(SkillsList);
}
}
}
return list;
}
Screenshot here:
I got answer for it:
1: Change SQL Query:
select concat('[', STUFF
(
(
SELECT top 15 '","'+ CAST(skillname AS VARCHAR(MAX))
from DNH_Master_Skills where SkillName LIKE '%' + #SkillName + '%'
FOR XMl PATH('')
),1,2,''
),'"]')
2: Change JSON Code:
From: response(data.d); TO: response(Array.parse(data.d));
Now its working feeling happy.

MVC4 Detailview from GridMvc.selectedData

I am trying to get the selected row of a MVCGrid and display the details in an modal dialog using a partialview.
I am getting the selected row via ajax:
$(document).ready(function(){
var selectedRow;
$(document).on('click', '.grid-mvc', function () {
pageGrids.PersonGrid.onRowSelect(function (e) {
// $.prompt(e.row.ID);
SendData(e.row);
});
});
});
The 'SendData'-function is:
function SendData(i) {
var data= i.ID;
$.ajax({
url: '/Home/Person',
contentType: "application/html; charset=utf-8",
type: "GET",
data: { "id": daten },
dataType: "html"
, success: function () {
ShowPersonDetails(data);
}
});
}
and the ShowPersonDetails(data) is like that:
function ShowPersonDetails(data) {
$(document).ready(function () {
$('#PersonDiv').load("Person?id=" + data);
$("#PersonDiv").prompt(
$("#PersonDiv").html(),
{
title: "some title",
buttons: { OK: 'true', Abbruch: 'false' },
position: { width: 800, height: 600 }
});
});
}
The controller:
[HttpGet]
public ActionResult Person(int id)
{
var pS = new DbAccess(MvcApplication.Connection).GetUserData(id);
var p = new Person();
if (pS.Rows.Count < 0)
{
return PartialView("Person");
}
p.Alter = pS.Rows[0].ItemArray[0].ToString();
p.Nachname = pS.Rows[0].ItemArray[5].ToString();
return PartialView("Person", p);
}
Any advice would be nice!
Greetings
PP
i did something like you are trying to do, so hope my code helps
in the grid, table, i put a link for details
<tr>
<td>
#Html.ActionLink("Details", "ActionDetails", new { id = Model.LstItems[x].ID }, new { #class = "detailsLink" })
</td>
</tr>
the javascript
$('#detailsDialog').dialog({
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons: {
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".detailsLink").button();
$(".detailsLink").click(function () {
linkObj = $(this);
var dialogDiv = $('#detailsDialog');
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
//open dialog
dialogDiv.dialog('open');
});
return false;
});
in somewhere in the view
<div id="detailsDialog" title="Offer Details">
</div>
the controller
public ActionResult ActionDetails(int id)
{
ItemEntity model = ItemEntity .GetBy(id);
return PartialView(model);
}
the partial view
#model YourNameSpace.Entities.ItemEntity
#using (Ajax.BeginForm("ActionDetails", "YourController", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "updateSuccess",
OnFailure = "showErrorMessage"
}, new { #id = "detailForm" }))
{
//your details for your item
}
hope this help you

Resources