I've been trying to complete a requirement which has a textbox where I need to do a autoComplete functionality. I have a Model which has two properties, Name and Value. So, I am a list of CityNames and their Id's. So on entering the name, system should get the Id. I've been trying alot but din't found any solution. Could anyone help me please!!
Here is my Controller
[HttpPost]
public JsonResult FillViewData(string term)
{
List<City> list = new List<City>()
{
new City{ Name = "Vijay", Id = 1 },
new City{ Name = "Ratan", Id = 2 },
new City{ Name = "Payo", Id = 3 },
new City{ Name = "Hari", Id = 4 },
new City{ Name = "Krish", Id = 5 }
};
var CityName = (from N in list
where N.Name.StartsWith(term)
select new { N.Name });
return Json(CityName, JsonRequestBehavior.AllowGet);
}
View:
#Html.TextBox("searchName", null,new { name = "txtSearch"})
JS:
<script type="text/javascript">
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
url: 'Home/FillViewData',
type: "POST",
dataType: JSON,
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
}
})
}
});
Change url format like this
url: '/Home/FillViewData',
Related
I have select2s, I fill these select2 with procedure. I fill select2 by saying return json on the controller side. But repetitive recordings are coming, where can I use DISTINCT for this?
JavaScript
$('#markaSelect').select2({
ajax: {
url: '/Home/MarkaGetir',
data: function (params) {
var query = {
q: params.term,
ModelAd: $('#modelselect').val(),
UreticiAd: $('#ureticiselect').val()
}
return query;
},
dataType: 'json',
type: "POST",
},
placeholder: 'Marka Seçiniz',
allowClear: true
});
Controller
public JsonResult MarkaGetir(string q = "", string MarkaAd = "", string ModelAd = "", string UreticiAd = "")
{
var lst = Vtİslemleri.Mmu(MarkaAd, ModelAd, UreticiAd);
lst.Select(x => x.Marka).Distinct();
return Json(new
{
results = lst.Select(x =>
new
{
id = x.Marka,
text = x.Marka
})
});
}
A short example: There are 4 of the Seat brand models, I want 1 to come when I shoot this.
I want to update a select list when the user selects a value in another select list. I've managed to get the first select list to call a get (or post) method on the model with a parameter, and can update the underlying data. But the second select list never shows the new values.
I'm not very experienced with asp.net, so what am I doing wrong?
Code below
.cshtml
<div>
<form method="post">
<select id="departureStation" asp-items="Model.DepartureStations" onchange="getDestinationStations()"></select>
<select id="destinationStation" asp-items="Model.DestinationStations"></select>
</form>
</div>
#section Scripts {
<script type="text/javascript">
function getDestinationStations() {
var selectedDepartureStationID = $("#departureStation").find(":selected").val();
console.log("selectedDepartureStationID = " + selectedDepartureStationID);
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
console.log("success - " + result);
},
error: function() {
console.log("failure");
}
})
}
</script>
}
.cs
public List<SelectListItem> DestinationStations
{
get
{
if (this._selectedDepartureStationID == -1)
return new List<SelectListItem>();
List<Models.Station> stations = new List<Models.Station>();
List<Models.RouteSegment> routeSegments = this._context.RouteSegments.Where(x => x.StationID == this._selectedDepartureStationID).ToList();
foreach (Models.RouteSegment routeSegment in routeSegments.DistinctBy(x => x.RouteID))
{
List<Models.RouteSegment> routeSegments2 = this._context.RouteSegments.Where(x => x.RouteID == routeSegment.RouteID).Include(x => x.Station).ToList();
stations.AddRange(routeSegments2.Select(x => x.Station));
}
return new List<SelectListItem>(stations.Distinct().ToList().Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList());
}
}
public IndexModel(MyViewContext context)
{
this._context = context;
}
public void OnGet()
{
this.DepartureStations = this._context.Stations.Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList();
}
public IActionResult OnGetDeparture(int selectedDepartureStationID)
{
this._selectedDepartureStationID = selectedDepartureStationID;
return Page();
}
Whenever your #departureStation select changes, your code will call getDestinationStations javascript code. Inside that function you are sending a request to your backend server to receive possible destination stations if I understood correctly. What you need to do here is when ajax request successes, add options dynamically based on your returned array or data.
I am assuming your "/Index?handler=Departure" returns a JSON like:
[
{
id: 1,
name: "station1"
},
{
id: 2,
name: "station2"
}
]
Check if code below works.
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
let destinationStationSelect = $('#destinationStationSelect');
let optionTemplate = $('<option></option>');
$.each(result, (index, element) => {
let option = optionTemplate.clone();
option.append(element.name);
option.attr('value', element.id);
destinationStationSelect.append(option);
});
},
error: function() {
console.log("failure");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I want to be able to display the ViewBag on view on button click event, this is my code:
[HttpPost]
public ActionResult SpecificWorkflowReport(Report2ListViewModel wf)
{
var getSpRecord = db.Mworkflow().ToList();
var getRecord = (from u in getSpRecord
select new Report2ListViewModel
{
WorkFlowType = u.WorkFlowType,
WorkflowInstanceId = u.WorkflowInst,
WorkFlowDescription = u.WorkFlowDesc,
}).ToList();
ViewBag.WorkflowType = wf.WorkFlowType;
ViewBag.WorkflowInstanceId = wf.WorkflowInst;
ViewBag.WorkFlowDescription = wf.WorkFlowDesc
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getRecord);
return Json(data);
}
i have tried this:
Worflow Type: #ViewBag.WorkflowType
Workflow Instance Id: #ViewBag.WorkflowInstanceId
Workflow Description: #ViewBag.WorkFlowDescription
My Javascript and json Call:
<script type="text/javascript">
$(function () {
var table = $("#reportTable").DataTable();
var url = $("#frmSpecificWorkflowReport").attr('action');
var str = $("#frmSpecificWorkflowReport").serialize();
$.ajax({
url: url,
type: "POST",
data: str,
cache: false,
dataType: "json",
success: function (_data) {
if (_data.f !== undefined) {
swal({
title: "Empty Result Set",
text: "No record found",
type: "info"
});
table.clear();
return false;
}
var arr = $.map(JSON.parse(_data), function (el) { return el
});
if (arr.length === 0) {
swal({
title: "Empty Result Set",
text: "No record found",
type: "info"
});
}
table.clear();
table.destroy();
$('#reportTable').dataTable({
data: arr,
columns: [
{ "data": "WorkFlowType" },
{ "data": "WorkflowInstanceId" },
{ "data": "WorkFlowDescription" },
],
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel',
{
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'LEGAL'
}
]
});
table = $("#reportTable").DataTable();
but the ViewBag values are always null on the view, any assistance will be appreciated. I just added Javascript and json call to the post, i want to be able to retrieve my stored data and display it anywhere on the view
#UwakPeter your code snippets is ok, but you are returning Json, may be you are calling this method via javascript, so the view is not updating, you need to reload the view, by the submit button.
If you are using javascript, you can pass your data list and model data as anonymous object, so that you don't need to use ViewBag. in client side by ajax success function you can grab them (WorkflowType, WorkflowInstanceId, WorkFlowDescription, Result)
[HttpPost]
public ActionResult SpecificWorkflowReport(Report2ListViewModel wf)
{
var getSpRecord = db.Mworkflow().ToList();
var getRecord = (from u in getSpRecord
select new Report2ListViewModel
{
WorkFlowType = u.WorkFlowType,
WorkflowInstanceId = u.WorkflowInst,
WorkFlowDescription = u.WorkFlowDesc,
}).ToList();
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getRecord);
return Json(new{
WorkflowType = wf.WorkFlowType,
WorkflowInstanceId = wf.WorkflowInst,
WorkFlowDescription = wf.WorkFlowDesc,
Result= data
}, JsonRequestBehaviour.AllowGet);
}
JS
$.ajax({
url: url,
type: "POST",
data: str,
cache: false,
dataType: "json",
success: function (_data) {
var workflowType=_data.WorkflowType; //set it to HTML control
var workflowInstanceId =_data.WorkflowInstanceId;
var workFlowDescription = _data.WorkFlowDescription;
$('#reportTable').dataTable({
data: _data.Result
});
}
)};
Try this,
#{
Layout = null;
ProjectMVC.Models.Record record= (ProjectMVC.Models.Record)ViewBag.Recorddetails;
}
...
Worflow Type: #record.WorkflowType
I can generate a Pie Chart Just like the picture by using the code below
<script>
var pieChartData = [
{ label: "Data 1", data: 16, color: "#62cb31", },
{ label: "Data 2", data: 6, color: "#A4E585", },
{ label: "Data 3", data: 22, color: "#368410", },
{ label: "Data 4", data: 32, color: "#8DE563", }
];
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByRegion"), pieChartData, pieChartOptions);
</script>
Now what I want to do is to generate the var data = [] dynamically from Controller. How to do this? Also the data is from the Database.
By Combining Pranav Patel and Ghanshyam Singh answers
I was able able to reach the desired output
Model
public class GenderPieChart_Model
{
public string GenderDesc { get; set; }
public int GenderID { get; set; }
}
Controller
public JsonResult Gender()
{
Dashboard_Layer data = new Dashboard_Layer();
var lst = data.Gender();
return Json(lst, JsonRequestBehavior.AllowGet);
}
Business Layer
public IEnumerable<GenderPieChart_Model> Gender()
{
List<GenderPieChart_Model> data = new List<GenderPieChart_Model>();
using (SqlConnection con = new SqlConnection(Connection.MyConn()))
{
SqlCommand com = new SqlCommand("dbo.sp_Project_DashBoard 4", con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
GenderPieChart_Model value = new GenderPieChart_Model();
value.GenderDesc = Convert.ToString(reader.GetValue(0));
value.GenderID = Convert.ToInt32(reader.GetValue(1));
data.Add(value);
}
}
return data;
}
View
<div class="flot-chart-content" id="_ByGender" style="height: 150px"></div>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "#Url.Action("Gender", "Dashboard")",
content: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = data;
var pieChartData = [];
$.each(data, function (i,v) {
pieChartData.push({ label: v.GenderDesc, data: v.GenderID, color: "#62cb31", });
})
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByGender"), pieChartData, pieChartOptions);
}
})
});
</script>
you can call when your controller on ready event and after getting data (returned Json from your controller) can process further. You can try like below
<script>
$(document).ready(function(){
$.ajax({
type: "POST", //GET or POST
url: "<YOUR URL>",
data: "<YOUR PARAMETER IF NEEDED>",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){ //data is your json returned from controller
var myData = JSON.parse(data);
//create your 'pieChartData' from object 'myData'
//pieChartData =
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByRegion"), pieChartData, pieChartOptions);
}
});
});
</script>
Its simple just return Json from your controller:
first create a model class for the properties
public class Chart
{
public string label{get;set;}
public string data{get;set;}
public string color{get;set;}
}
MVC action method:-
public JsonResult Chart()
{
List<Chart> chartList=new List();
// Code to fetch Data in List chartList
return Json(chartList,JsonRequestBehaviour.AllowGet);
}
Ajax Call:-
<script>
$(document).ready(function(){
$.ajax({
type: "POST", //GET or POST
url: "/Controller/Chart",
data: "<YOUR PARAMETER IF NEEDED>",
dataType: "json",
success: function(data){
$.each(data,function(i,index){
// Code to plot Chart here
});
}
});
});
</script>
I have a asp.net application where i have kendo ui treeview in aspx page. on document ready, i am calling a method in the aspx page for the data. The kendo treeview is not loading the data dynamically. It only shows the loading indicator. When we provide the same json data in aspx page itself, it works fine.
Here is the code
[System.Web.Services.WebMethod]
public static string MakeTreeData()
{
return "[{ text: \"Node1\", items: [{text:\"Child1\"},{text:\"Child2\"},{text:\"Child3\"}]}]";
}
script
var $jQuery2_1 = jQuery.noConflict(true);
$jQuery2_1(document).ready(function () {
$jQuery2_1.ajax({ url: "Default.aspx/MakeTreeData",
contentType: "application/json; charset=utf-8",
type: "post",
success: function (result) {
var viewModel = new kendo.data.HierarchicalDataSource({
data: JSON.parse(result.d),
schema: {
model: {
children: "items"
}
}
});
$jQuery2_1("#treeview").kendoTreeView({
dataSource: viewModel,
dataTextField: "text"
});
},
error: function (e) {
console.log(e);
}
});
});
Thanks
Updating the method and script like below solved the issue
MakeTreeData
[System.Web.Services.WebMethod]
public static string MakeTreeData()
{
JavaScriptSerializer js = new JavaScriptSerializer();
var parentNodes = new List<Node>();
var parent = new Node() { Id = "1", Text = "Parent 1", Nodes = new List<Node>() };
var child = new Node() { Id = "2", Text = "Child 1", Nodes = new List<Node>() };
parent.Nodes.Add(child);
parentNodes.Add(parent);
return js.Serialize(parentNodes);
}
Script
<div class="demo-section k-content">
<div id="treeview"></div>
</div>
<script>
$(document).ready(function () {
$.ajax({
url: "Default.aspx/MakeTreeData",
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (result) {
var jsonData = JSON.parse(result.d);
var viewModel = new kendo.data.HierarchicalDataSource({
data: JSON.parse(result.d),
schema: {
model: {
children: "Nodes"
}
}
});
$("#treeview").kendoTreeView({
dataSource: viewModel,
dataTextField: "Text"
});
},
error: function (e) {
console.log(e);
}
});
});
</script>