How to populate a #html.dropdownlist mvc helper using JSon - 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);
}

Related

Values not displaying in Listbox from database using mvc5

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

Format JSON string before displaying it in MVC? (with datatables)

Got a nice JSON problem over here;
I don't know how to go about formatting date, timespan, decimals etc before sending it to the view in MVC. I'm using the datatables jQuery plugin, and my 'DataHandler' method returns a JSON object as source for the datatable.
When I was processing the data and filtering client-side it was pretty straightforward, but now I'm processing the data on the server-side.
Controller:
public JsonResult DataHandler(DTParameters param)
{
try
{
var dtsource = new List<spRegistrations_Result>();
using (entities dc = new entities())
{
dtsource = dc.spRegistrations().ToList();
}
List<String> columnSearch = new List<string>();
foreach (var col in param.Columns)
{
columnSearch.Add(col.Search.Value);
}
List<spRegistrations_Result> data = new ResultSet().GetResult(param.Search.Value, param.SortOrder, param.Start, param.Length, dtsource, columnSearch);
int count = new ResultSet().Count(param.Search.Value, dtsource, columnSearch);
DTResult<spRegistrations_Result> result = new DTResult<spRegistrations_Result>
{
draw = param.Draw,
data = data,
recordsFiltered = count,
recordsTotal = count
};
return Json(result);
}
catch (Exception ex)
{
return Json(new { error = ex.Message });
}
}
Table initialization:
var table = $('#myTable').DataTable({
responsive: true,
"serverSide": true,
"ajax": {
"type": "POST",
"url": '/Table/DataHandler',
"contentType": 'application/json; charset=utf-8',
'data': function (data) { return data = JSON.stringify(data); }
},
"drawCallback": function(settings){
$('.card').hide();
},
"paging": true,
"deferRender": true,
"columns": [
{ "data": "RegId" },
{ "data": "PresenceDate" }, etc...
Model:
public int RegId { get; set; }
public System.TimeSpan StartTime { get; set; }
public System.TimeSpan EndTime { get; set; }
public System.DateTime PresenceDate { get; set; }
This is how it looks when the table is displayed
As you can see, the date is not very nicely formatted, and is the reason that I want to format the data before displaying it. Same goes for a couple of TimeSpan objects etc that I eventually want to show in the table.
I'm still pretty new to ajax, and don't know how to go about this the easiest way. Thanks for any input !
You could use the columns.render property to define the content of the table cell, using a custom js function to format the date. Something like:
...
"render": function ( data, type, full, meta ) {
var date = new Date(parseInt(data.substr(6), 0));
return ISODateString(date);
}
The function to format the date dd/mmm/yyyy:
function ISODateString(d) {
function pad(n) { return n < 10 ? '0' + n : n }
return pad(d.getDate()) + '/' + pad(d.getMonth() + 1) + '/' + d.getFullYear();
}

Pass data from controller to view via JSONResult

I'd like to send ViewModel from controller to view in JSON format.
Controller:
public ActionResult Select(int pageLimiter)
{
var viewModel = new ArticlesViewModel
{
Articles = this.Service.GetArticles(0, 0, 0),
ArticlesTotal = this.Service.CountArticles(0),
Pages = new List<string>
{
"1", "2", "3"
}
};
return Json(viewModel, JsonRequestBehavior.AllowGet);
}
View:
<ul class="articleList">
#if (#Model != null)
{
foreach (var article in #Model.Articles)
{
<li>
<header>#article.Title</header>
<nav>
<span>#article.AuthorName</span> |
<time>#article.PublishDate.ToString("")</time> |
<span>#article.CategoryName</span> |
<span>#article.Comments Comments</span>
</nav>
<section>
#article.Content
</section>
</li>
}
}
</ul>
<script type="text/javascript">
$(document).ready(function () {
GetArticles(5);
$("#selectPager").change(function () {
var selectedItem = "";
$("#selectPager option:selected").each(function () {
selectedItem = $(this).text();
});
GetArticles(selectedItem);
});
});
function GetArticles(pageLimitValue) {
$.ajax(
{
url: "/Articles/Select",
dataType: "json",
data: { pageLimiter: pageLimitValue },
async: true,
beforeSend: function () {
alert("before");
},
complete: function (data) {
#Model = SOME_MAGIC_TRICKS
}
});
}
As you can see, in the complete event are words SOME_MAGIC_TRICKS. In this place I'd like to set #Model obtained from controller. Is it possible at all? How to insert data from ajax result to view model (it's null by default)?
You are trying to modify server variable from client's code. It's not possible.
If you want to re-render your page's content on complete, you may render <ul class="articleList"> with PartialView and return same partial view instead of JsonResult. Further, oncomplete handler will update your <ul class="articleList"> with returned content.
You can send data doing serialize it may be like:
public ActionResult Select(int pageLimiter)
{
var viewModel = new ArticlesViewModel
{
Articles = this.Service.GetArticles(0, 0, 0),
ArticlesTotal = this.Service.CountArticles(0),
Pages = new List<string>
{
"1", "2", "3"
}
};
string myjsonmodel = new JavaScriptSerializer().Serialize(viewModel );
return Json(jsonmodel = viewModel, JsonRequestBehavior.AllowGet);
}
dont forget using using System.Web.Script.Serialization;
Edit:
To deserialize object try this:
#{
JavaScriptSerializer jss= new JavaScriptSerializer();
User user = jss.Deserialize<User>(jsonResponse);
}

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 return multiple variables with jsonresult asp.net mvc3

How to return multiple variables on JsonResult method
for example i want to return this two variables:
string result = "Successed";
string ID = "32"
I know how to return only one string:
return Json("Inserted");
public ActionResult YourAction()
{
var result=new { Result="Successed", ID="32"};
return Json(result, JsonRequestBehavior.AllowGet);
}
EDIT : As per the comment "How to get this data in client"
You can use getJSON from view to get this data like this
$(function(){
$.getJSON('YourController/YourAction', function(data) {
alert(data.Result);
alert(data.ID);
});
});
Make sure you have jQuery loaded in your view for this code to work.
Return an anonymous object.
return Json( new { Result = result, Id = ID } );
I normally do something like this:
public enum NoticeTypes
{
Default,
UpdateComplete,
ResponsePending,
Notice,
Error,
Redirect,
WaitAndRetryAttempt
}
public class AjaxJsonResponse
{
public UserNotice Notice { get; set; }
public object Data { get; set; }
private AjaxJsonResponse() { }
public static JsonResult Create(UserNotice Notice,object Data)
{
return new JsonResult()
{
Data = new
{
Notice = Notice,
Data = Data
}
};
}
}
So that I can write my javascript to always expect ajax calls to return data in a certain format.
return AjaxResponse.Create(NoticeTypes.UpdateComplete, new
{
Result = result,
Id = ID
});
Now you can do things like an Ajax Complete global handler that can intercept things like Redirect or WaitAndRetry before the normal handler gets it, and to have a standard way of communicating additional information about the returned data that is the same across your application.
On your controller use something like this:
var result = new { data= stuff, data2 = otherstuff };
return Json(result, JsonRequestBehavior.AllowGet);
If you are using .ajax() on your JavaScript you can use your data acessing like this:
$.ajax(
{
url: '/Controller/Method/',
type: 'POST',
data: 'data=' + data,
success: function (result) {
$('#id').html("");
$(result.data).appendTo('#id');
$('#id2').html("");
$(result.data2).appendTo('#id2');
$('#id').show();
$('#id2').show();
}
});
1. Return as collection inside anonymous type
This is the java script/ajax call and the complete html.
< script type = "text/javascript" >
$(document).ready(function() {
$("#ddlProduct").hide();
$("#ddlRegion").change(function() {
$("#ddlProduct").show();
$("#ddlProduct").empty();
$.ajax({
type: "Post",
url: "#Url.Action("
GetProducts ")",
dataType: "Json",
data: {
id: $("#ddlRegion").val()
},
success: function(jsonData) {
console.log($(jsonData).length);
if ($(jsonData.ProductList).length == 0) {
$("#divProduct").hide();
} else {
$("#divProduct").show();
}
$.each(jsonData.ProductList, function(i, Product) {
$("#ddlProduct").append('<option value=" ' + Product.Value + ' ">' + Product.Text + '</option>');
});
if ($(jsonData.FlavourList).length == 0) {
$("#divFlavour").hide();
} else {
$("#divFlavour").show();
$.each(jsonData.FlavourList, function(i, flavour) {
$("#ddlFlavour").append('<option value=" ' + flavour.Value + ' ">' + flavour.Text + '</option>');
});
}
},
error: function(ex) {
alert("Failed to return Products <br/>");
}
});
return false;
})
}); //Document Ready Ends
< /script>
#{ ViewBag.Title = "Products Drop Down Demo"; }
<h2>Products Drop Down Demo</h2>
#using (Html.BeginForm()) {
<div>#Html.Label("Select Region:")</div>
<div class="editor-field">
#if (ViewData.ContainsKey("Region")) { #Html.DropDownList("ddlRegion", ViewData["Region"] as List
<SelectListItem>) }
</div>
<div id="divProduct" hidden="hidden">
<br />
<div>
Select a Product:
</div>
<div>
#Html.DropDownList("ddlProduct", new SelectList(string.Empty, "Value", "Text"), "Please select a Product", new { style = "width:250px", #class = "dropdown1" })
</div>
</div>
<div id="divFlavour" hidden="hidden">
<div>
<br />Select a Flavour:
</div>
<div>
#Html.DropDownList("ddlFlavour", new SelectList(string.Empty, "Value", "Text"), "Please select a Flavour", new { style = "width:250px", #class = "dropdown1" })
</div>
</div>
}
This is the controller action that returns the data
I tested and it is working.
public ActionResult LoadRegion()
{
List<SelectListItem> Regions = new List<SelectListItem>();
Regions.Add(new SelectListItem { Text = "Select A Region", Value = "0" });
Regions.Add(new SelectListItem { Text = "Asea", Value = "1" });
Regions.Add(new SelectListItem { Text = "Australia", Value = "4" });
Regions.Add(new SelectListItem { Text = "America", Value = "5" });
Regions.Add(new SelectListItem { Text = "Europe", Value = "6" });
ViewData["Region"] = Regions;
return View();
}
public JsonResult GetProducts(string id)
{
List products = new List();
List flavours = new List();
products.Add(new SelectListItem { Text = "Select Product", Value = "0" });
products.Add(new SelectListItem { Text = "Cheese", Value = "1" });
products.Add(new SelectListItem { Text = "Sause", Value = "2" });
products.Add(new SelectListItem { Text = "Veberage", Value = "3" });
products.Add(new SelectListItem { Text = "Snacks", Value = "4" });
flavours.Add(new SelectListItem { Text = "Select Flavour", Value = "0", Selected = true });
flavours.Add(new SelectListItem { Text = "Sweet", Value = "1" });
flavours.Add(new SelectListItem { Text = "Sour", Value = "2" });
flavours.Add(new SelectListItem { Text = "Spicy", Value = "3" });
var myResult = new
{
ProductList = products,
FlavourList = flavours
};
return Json(myResult, JsonRequestBehavior.AllowGet);
}
Let me know if you have any issue running this code.
Thanks
Premjeet
You should return an object with multiple properties:
return Json(new {
result,
ID
});
The JSON serializer will convert C# anonymous types into JSON object literals.
In Action method :
Using new keywork
var genericResult = new { homeworkData = homework, attachmentData = homeworkAttachment };
var result = this.Json(genericResult, JsonRequestBehavior.AllowGet);
return result;
In jquery side :
function getHomewrokDetailResponse(dataSent, result) {
if (result && result.homeworkData) {
homeworkId = result.homeworkData.DASH_EMPLOYEE_HOMEWORK_ID;
....
}