Values not displaying in Listbox from database using mvc5 - json

in controller json method getting columnnames (Account,EmailTo,Subject,MessageContent) like this in ReportColumnsList ..but i need to pass these values in view page and display in listbox..
data is getting as [Object Object] and also displaying in listbox like this..
please give me solution regarding this..
Thanks & Regards
in Controller part :-
[AllowAnonymous]
public ActionResult GetColumnsByFavouriteReport(ReportsModel Model,string Columns)
{
List<Report> ReportColumnsList = MCPAdminControllerPageObject.GetColumnsByReportName(Columns);
return Json(ReportColumnsList, JsonRequestBehavior.AllowGet);
}
In view Part:-
$(document).ready(function () {
$('#FavouriteReports').change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("GetColumnsByFavouriteReport", "MCPAdmin")',
data: { Columns: $('#FavouriteReports').val() },
datatype: "json",
traditional: true,
success: function (data) {
$('#SelectedFields').empty();
$.each(data, function (key, val) {
$('#SelectedFields').append('<option id="' + key + '">' + val + '</option>');
})
}
});
});
#Html.ListBoxFor(m => m.SelectedFields, new SelectList(new[] { "" }), new { #class = "form-control editable" })

Let me assume Your model class Report
public class Report {
public int ReportId { get; set; }
public Name ReportName { get; set; }
}
Inside your ajax method
if(data!=null) {
$('#SelectedFields').empty();
var dd = null ;
$.each(data, function (key, val) {
dd += "<option " + " value=" + val.ReportId + ">" + val.ReportName + "</option>";
});
//append to given id
$('#SelectedFields').append(dd);
}
I hope this will help your, bind your dropdown list

Related

Update Model and Display Updated Data in html table

I have a simple MVC application in which I am displaying data from the controller. and I want to show new data derieved from the call to the controller method.In other words, I am setting some default data to the html table and I want to change it using an Ajax call on button click. How can I do this, I can Share the code as follows :
The Model is :
public class Employee
{
public string Name { get; set; }
public string Surname { get; set; }
}
The Controller is :
public class SendAjaxParameterController : Controller
{
// GET: SendAjaxParameter
public ActionResult GetTheData()
{
List<Employee> Employee_Details = new List<Employee>();
Employee_Details = DefaultValues();
return View(Employee_Details);
}
public List<Employee> DefaultValues()
{
List<Employee> Employee_Details = new List<Employee>();
Employee emp = new Employee
{
Name = "John",
Surname = "Doe"
};
Employee emp1 = new Employee
{
Name = "Mary",
Surname = "Addinson"
};
Employee_Details.Add(emp);
Employee_Details.Add(emp1);
return Employee_Details;
}
[HttpPost]
public ActionResult Ajax_GetParameter(string name)
{
string nameofEmp = name;
List<Employee> Employee_Details = new List<Employee>();
if (name == "Monica")
{
Employee emp = new Employee
{
Name = "John",
Surname = "Doe"
};
Employee emp1 = new Employee
{
Name = "Mary",
Surname = "Addinson"
};
Employee_Details.Add(emp);
Employee_Details.Add(emp1);
}
else
{
Employee emp = new Employee
{
Name = "Robert",
Surname = "Doe"
};
Employee emp1 = new Employee
{
Name = "Monica",
Surname = "Addinson"
};
Employee_Details.Add(emp);
Employee_Details.Add(emp1);
}
return Json(new { success = true, data = Employee_Details },JsonRequestBehavior.AllowGet);
}
}
The View is :
#model IEnumerable<datatableViewTocontroller.Models.Employee>
#{
ViewBag.Title = "GetTheData";
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>GetData</title>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Scripts/datatable/DataTables-1.10.20/css/dataTables.jqueryui.min.css" rel="stylesheet" />
#section Scripts{
<script src="~/Scripts/datatable/DataTables-1.10.20/js/jquery.dataTables.min.js"></script>
<script src="~/Scripts/datatable/DataTables-1.10.20/js/dataTables.jqueryui.min.js"></script>
<script>
var nameValue = "";
var dttable = $("#mytable").DataTable();
$("#btn_GetData").click(function () {
if (confirm("Do you want to continue?")) {
nameValue = "Monica";
$.ajax({
type: "POST",
url: "/SendAjaxParameter/Ajax_GetParameter",
data: '{name:"' + nameValue + '"}',
contentType: "application/json; utf-8",
dataType: "json",
success: function (data) {
if (data.success) {
alert(data);
}
}
});
}
else {
nameValue = "Not Monica";
$.ajax({
type: "POST",
url: "/SendAjaxParameter/Ajax_GetParameter",
data: '{name:"' + nameValue + '"}',
contentType: "application/json; utf-8",
dataType: "json",
success: function (data) {
}
});
}
});
</script>
}
</head>
<body>
<div id="table-div">
<table id="mytable">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
#foreach (var modeldata in Model)
{
<tr>
<td>#modeldata.Name</td>
<td>#modeldata.Surname</td>
</tr>
}
</tbody>
</table>
</div>
<br />
<button id="btn_GetData" style="float:right;">GetData</button>
</body>
</html>
So, The question is How can I assign new data to the table ? Please Help!
You can use each loop to iterate through your json data which you have recieve from server and then use += to append new row to some variable.Then to add these row to your tbody you can use .html().
Demo Code :
//your response
var data = [{
"Name": "abc",
"Surname": "xyz"
}, {
"Name": "abcd",
"Surname": "xyzd"
}]
var html = "";
//loop through data
$.each(data, function(index, value) {
//append row
html += '<tr><td>' + value.Name + '</td>' + '<td>' + value.Surname + '</td><td><button name="edit">Edit</button></td></tr>';
});
//add row to tbody
$("#mytable tbody").html(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table-div">
<table id="mytable">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<!--data will come here-->
<tr>
<td>#modeldata.Name</td>
<td>#modeldata.Surname</td>
</tr>
</tbody>
</table>
</div>
I think the only problem is to clear the previously loaded data. You can clear the div retaining that data and then load the retrieved data using jQuery:
$('#div-or-row-id').html(""); //Clear div
On the other hand, you can also try the following approach or replace the table data by setting table data by response of AJAX call:
$.ajax({
//code omitted for brevity
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
SetData(data);
},
error: function (data) { onError(data); }
});
function SetData(data) {
$("#div-or-row-id").html(data); // HTML DOM replace
}
You can rerender table structure using Jquery after Ajax success call.
Just make Table Td structure and append in the respective div.
e.g.
$('You Parent div').empty().append('new structure');
as per your answer I've updated the code like :
$.ajax({
type: "POST",
url: "/SendAjaxParameter/Ajax_GetParameter",
data: '{name:"' + nameValue + '"}',
contentType: "application/json; utf-8",
dataType: "json",
success: function (data) {
if (data.success) {
alert(data);
var len = data.length;
var txt = "";
if (len > 0)
{
for (i = 0; i < len; i++) {
if(i==0){
txt +="<table id='mytable'>" +
"<thead>" +
"<tr>" +
"<th>Name</th>" +
"<th>Surname</th>" +
"</tr>" ;
}
txt += "<tr><td>" + data[i].Name + "</td><td>" + data[i].Surname + "</td></tr>"
}
if (txt != "") {
$("#mytable").empty().append(txt).removeClass("hidden");
}
}
}
}
});

How to Insert Data Into Database Table Using jQuery in ASP.Net MVC4

im working on ASP.NET MVC 4 project. well i already insert data into a SQL Server database using jQuery using a post method in .
Now im trying to insert data into 2 tables using the same view, my problem is that i can't passing multiple POST parameters to Web API Controller Method. here is my js function and my controller code, ill apreciate your help
var add_ClientPreste = function () {
var dataContrat = {
REFCONTRAT : 'mc1' ,
DATECREATION : '2016-05-23',
DATEFINCONTRAT : '2016-05-23'
};
var dataClient = {
C_IDCLIENTGROUPE : 11 ,
C_IDLOCALITE:332,
DATECREATION : '2016-05-23',
DATEMODIFICATION : '2016-05-23',
CODECLIENTPAYEUR : '999999999' ,
NOMCLIENTPAYEUR : 'morad'
};
$.ajax({
type: 'POST',
url: 'add_ClientPayeurContrat',
dataType: 'json',
data:{dataClient},
success: function (data) {
if(data==0) {
alert("enregistrement avec success : " );
}
else {
alert("error : "+ data );
}
},
error : function(data1) {
alert("aaaaaaaaaaaaaa " +data1);
}
});
}
$('#btntest').on('click', function () {
add_ClientPreste();
});
$('#btntest').on('click', function () {
add_ClientPreste();
});
Controller code
[HttpPost]
public ActionResult add_ClientPayeurContrat(SIG_CLIENTPAYEUR dataClient, SIG_CONTRAT dataContrat)
{
string msg = "";
try
{
ModSigma1.SIG_CLIENTPAYEUR.Add(dataClient);
ModSigma1.SIG_CONTRAT.Add(dataContrat);
ModSigma1.SaveChanges();
msg = "0";
}
catch (Exception ex)
{
msg = ex.Message;
}
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
var add_ClientPreste = function () {
var dataContrat = {
REFCONTRAT : 'mc1' ,
DATECREATION : '2016-05-23',
DATEFINCONTRAT : '2016-05-23'
};
var dataClient = {
C_IDCLIENTGROUPE : 11 ,
C_IDLOCALITE:332,
DATECREATION : '2016-05-23',
DATEMODIFICATION : '2016-05-23',
CODECLIENTPAYEUR : '999999999' ,
NOMCLIENTPAYEUR : 'morad'
};
$.ajax({
type: 'POST',
url: 'add_ClientPayeurContrat',
dataType: 'json',
data:{dataClient: dataClient},
success: function (data) {
if(data==0){
alert("enregistrement avec success : " );
}
else {
alert("error : "+ data );
}
},
error : function(data1){
alert("aaaaaaaaaaaaaa " +data1);
}
});
}
$('#btntest').on('click', function () {
add_ClientPreste();
});
$('#btntest').on('click', function () {
add_ClientPreste();
});
//controller code
[HttpPost]
public ActionResult add_ClientPayeurContrat(SIG_CLIENTPAYEUR dataClient, SIG_CONTRAT dataContrat)
{
string msg = "";
try
{
ModSigma1.SIG_CLIENTPAYEUR.Add(dataClient);
ModSigma1.SIG_CONTRAT.Add(dataContrat);
ModSigma1.SaveChanges();
msg = "0";
}
catch (Exception ex)
{
msg = ex.Message;
}
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
you did not add dataClient: dataClient in ajax.
so please add this.
Hope this will help you.

Save multiple selected data

With this code on my form I want to save the selected Cars (all its data - id and description):
<div class="editor-field">
#Html.DropDownListFor(model => model.Cars, new SelectList(Model.ListCars, "Description", "Description"), new { id = "myCars", multiple="multiple" })
#Html.ValidationMessageFor(model => model.Cars)
</div>
but when I check if Model.IsValid, it's set to false and in my view I got this message: The value '(selected)' is invalid.
Can anyone tell me why and how can I solve this?
My viewModel:
public ICollection<Car> Cars;
public ICollection<Car> ListCars; //it's populated somewhere
My Car.cs:
public int Id { get; set; }
public string Description { get; set; }
I developed a solution that doesn't consider a good practice, but at least it solved my problem. Basically my logic is as follows:
Use a plugin for the dropdown helper
Have somewhere a hidden div with all the selectable values ​​passed to the dropdown helper (id and description)
When there is a change in the selected dropdown through JS item, "select" in the hidden div desired values ​​by assigning them a specific name in order to be saved
Like this:
1. Use a plugin for the dropdown helper:
I used this JS plugin (v0.6) on my dropdowns, so I have this changes:
My dropdown helper:
#Html.DropDownListFor(model => model.Cars, new SelectList(Model.ListCars, "Description", "Description"), new { id = "myCars", #class = "isCheckList", multiple="multiple" })
In my JS:
$(document).ready(function () {
$(".isCheckList").dropdownchecklist({ firstItemChecksAll: true, width: 350 });
});
2. Have somewhere a hidden div with all the selectable values ​​passed to the dropdown helper (id and description):
<div id="carsHidden" style="display:none">
#foreach (Caritem in Model.ListCars)
{
<div id="#(item.Id)">
#Html.HiddenFor(modelItem => item.Id, new { data_Name = "Id" })
#Html.HiddenFor(modelItem => item.Description, new { data_Name = "Description" })
</div>
}
</div>
3. When there is a change in the selected dropdown through JS item, "select" in the hidden div desired values ​​by assigning them a specific name in order to be saved:
For this, I add an event onchange to my dropdown helper and manager that selection:
$(".isCheckList").on("change", function (e, data) {
var hiddenDivId = $(this).data("hiddendivid");
var fieldName = $(this).data("fieldname");
selectManagement($(this), data, hiddenDivId, fieldName);
});
function selectManagement(e, data, hiddenDivId, fieldName) {
$(e).children().each(function () {
if ($(this).attr("value") == $(data).attr("value")) {
if ($(this).attr("selected")) {
$("#" + hiddenDivId + " #" + $(this).attr("value")).addClass("IsSelected");
selectComponent(hiddenDivId, fieldName);
}
else {
$("#" + hiddenDivId + " #" + $(this).attr("value")).removeClass("IsSelected");
unselectComponent(hiddenDivId);
updateRowsIds(hiddenDivId, fieldName);
}
return false;
}
});
}
function unselectComponent(hiddenDivId) {
$("fieldset").each(function () {
if ($(this).find("div#" + hiddenDivId).exists()) {
$("div#" + hiddenDivId).children().each(function () {
if ($(this).hasClass("IsSelected") == false) {
$(this).find("input").each(function () {
$(this).attr("name", null);
$(this).attr("id", null);
});
}
});
}
});
}
function selectComponent(hiddenDivId, fieldName) {
$("fieldset").each(function () {
if ($(this).find("#" + hiddenDivId + " .IsSelected").exists()) {
var index = 0;
$("#" + hiddenDivId + " .IsSelected").each(function () {
$(this).children().each(function () {
if ($(this).is("input")) {
$(this).attr("name", fieldName + "[" + index + "]." + $(this).data("name"));
$(this).attr("id", fieldName + "_" + index + "_" + $(this).data("id"));
}
});
index++;
});
}
});
}
function updateRowsIds(hiddenDivId, fieldName) {
$("#" + hiddenDivId + " div.IsSelected").each(function (index) {
$(this).find("input").each(function () {
$(this).attr("name", fieldName + "[" + index + "]." + $(this).data("name"));
});
});
}
So now, always I select a Car I will save its Description and ID

Autcomplete using Jquery Ajax in JSP

I am trying to follow this example
and I have the following in JSP page
(getData.jsp)
Department t = new Department ();
String query = request.getParameter("q");
List<String> tenders = t.getDepartments(query);
Iterator<String> iterator = tenders.iterator();
while(iterator.hasNext()) {
String deptName= (String)iterator.next();
String depto = (String)iterator.next();
out.println(deptName);
}
How can I use the above to use in Jquery autcomplete? When I tried there was no output coming.
My Jquery autoComplete code
<script>
$(function() {
$( "#dept" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getData.jsp",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.<??>, function( item ) {
return {
label: item.name + (item.<??> ? ", " + item.<??> : "") + ", " + item.<??>,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
alert(ui.item.label);
}
});
});
</script>
Is your response in JSON format?
Here's what I do when I use Jquery UI Autocomplete:
Create a class whose parameters are the ones you will use when you say item.name
public string Pam1{ get; set; }
public string Pam2{ get; set; }
public string Pam3{ get; set; }
public SomeResponse(string SomePam)
{
// Pam1 = ???
// Pam2 = ???
// Pam3 = ???
}
In your handler:
context.Response.ContentType = "application/json";
string query = (string)context.Request.QueryString["query"];
var json = new JavaScriptSerializer();
context.Response.Write(
json.Serialize(new SomeResponse(query))
);
context.Response.Flush();
context.Response.End();
EDIT
The javascript (Here is an example where the user can choose more than one option, separated by coma. If you don't want that, remove it.) txt_autocomplete is the class of the TextBox.
$(function () {
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$(".txt_autocomplete")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
source: function (request, response) {
$.getJSON("handlers/autocomplete.ashx?query=" + extractLast(request.term), {
term: extractLast(request.term)
}, response);
},
search: function () {
var term = extractLast(this.value);
if (term.length < 2) {
return false;
}
},
focus: function () {
return false;
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.Pam1);
terms.push("");
this.value = terms.join(", ");
console.log("Pam1 is :" + ui.item.Pam1 + " Pam2 is: " + ui.item.Pam2 + " Pam 3 is : " + ui.item.Pam3);
return false;
}
});
});

How to populate a #html.dropdownlist mvc helper using JSon

I have a <select> which is loaded by a JSon. But I want to use "#html.dropdownlist helper" instead. My Json is:
function LoadSites() {
$("SelectSite").html("");
$.getJSON("/Pedido/GetSite", null, function (data) {
$("#SelectSite").append("<option value=0>Selecione...</option>");
$.each(data.Result, function (index, site) {
$("#SelectSite").append("<option value='" + site.Id + "'>" + site.Nome + "</option>");
});
});
this Json populate this...
<select id="SelectSite"></select>
My Controller:
[HttpGet]
public JsonResult GetSite()
{
Repository<Site> siteRepo = new Repository<Site>( unitOfWork.Session );
return this.Json( new { Result = siteRepo.All() }, JsonRequestBehavior.AllowGet );
}
I want my code more reusable and self-documenting.
How can I send the object "site" from JSon to "cshtml" using dropdownlist to do something like #html.dropdownlist(site.id, site.Nome)???
Is there a way?
Tks guys.
In your view:
#Html.DropDownListFor(x => x.SiteId, new SelectList(Enumerable.Empty<SelectListItem>()))
where SiteId is a property of your view model which will receive the selected site id when the form is submitted.
and then you could populate this dropdown using AJAX:
$(function() {
$.getJSON('#Url.Action("GetSite", "Pedido")', function(result) {
var ddl = $('#SiteId');
ddl.empty();
$(result).each(function() {
ddl.append(
$('<option/>', {
value: this.Id
}).html(this.Nome)
);
});
});
});
and the controller action that would return the JSON data:
public ActionResult GetSite()
{
var sites = new[]
{
new { Id = "1", Nome = "site 1" },
new { Id = "2", Nome = "site 3" },
new { Id = "3", Nome = "site 3" },
};
return Json(sites, JsonRequestBehavior.AllowGet);
}