I have a system Every user has role and Id And some user has parent , i want to show this tree by Jstree but when I fetch data from database, just show 2 level for me,how can i expand it to show whole tree in my system?
This is My Action In Controller:
public async Task<IActionResult> Index2Async()
{
List<TreeViewNode> nodes = new List<TreeViewNode>();
//Loop and add the Parent Nodes.
//get roots
foreach(var user in userManager.Users)
{
var checkUserIsEmployee = applicationDbContext.EmployeeInRoles.Where(s => s.UserId == user.Id).ToList().Count;
if (checkUserIsEmployee>0)
{
continue;
}
else
{
nodes.Add(new TreeViewNode { id = user.Id, parent = "#", text = user.Name + " " + user.Family });
}
}
//end get roots
//Loop and add the Child Nodes.
//get child
foreach (var user in userManager.Users)
{
var Employee = applicationDbContext.EmployeeInRoles.ToList();
foreach (var item in Employee)
{
if (user.Id == item.UserId)
{
var ParentRole = roleManager.Roles.SingleOrDefault(s => s.Id == item.RoleId);
foreach(var parent in userManager.Users)
{
if (await userManager.IsInRoleAsync(parent, ParentRole.Name))
{
nodes.Add(new TreeViewNode { id = user.Id + "-" + parent.Id, parent = parent.Id, text = user.Name+" "+user.Family });
}
}
}
}
}
//end get child
//Serialize to JSON string.
ViewBag.Json = JsonConvert.SerializeObject(nodes);
return View();
}
This is cshtml file (Index2):
<link rel="stylesheet" href="~/jstree/dist/themes/default/style.min.css" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/jstree/dist/jstree.min.js"></script>
<div style="color:#fff" id="jstree">
</div>
<form method="post" asp-controller="Admin" asp-action="Index2">
<input type="hidden" name="selectedItems" id="selectedItems" />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
jQuery(function ($) {
$('#jstree').on('changed.jstree', function (e, data) {
var i, j;
var selectedItems = [];
var postedItems = [];
for(i = 0, j = data.selected.length; i < j; i++) {
//Fetch the Id.
var id = data.selected[i];
//Remove the ParentId.
if(id.indexOf('-') != -1){
id = id.split("-")[1];
}
//Add the Node to the JSON Array.
selectedItems.push({
text: data.instance.get_node(data.selected[i]).text,
id: id,
parent: data.node.parents[0]
});
}
//Serialize the JSON Array and save in HiddenField.
$('#selectedItems').val(JSON.stringify(selectedItems));
}).jstree({
"core": {
"themes": {
"variant": "large"
},
"data": #Html.Raw(ViewBag.Json)
},
"checkbox": {
"keep_selected_style": false
},
"plugins": ["wholerow", "checkbox"],
});
});
This is model:
public class TreeViewNode
{
public string id { get; set; }
public string parent { get; set; }
public string text { get; set; }
}
And the result is below:
Related
I have make field with picklist value and retrieve the sobject list and show in the form but with list i got the other custom object to that i don't want to show.
Component:
this is just a component to show the list.
<div class="slds-form-element slds-size_1-of-2 slds-float_left slds-p-around_xx-small">
<lightning:select name="Objects" label="Select SObject:" aura:id="onjId" value="
{!v.selectedValue}">
<aura:iteration aura:id="list" items="{!v.option}" var="objectname">
<option value="{!objectname}" text="{!objectname}"/>
</aura:iteration>
</lightning:select>
</div>
Controller:
helper.getObjectTypePicklist(component);
helper:(in comment I tried but not get the result)
getObjectTypePicklist: function(component) {
var action = component.get("c.getObjectName");
// var list = component.get("v.option");
// component.find("list").set("v.option", Replace(list,'Select Name Where
%skyvvasolutions__',''));
// action.setParams({
// Replace(list, 'skyvvasolutions__', '')
// });
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var allValues = response.getReturnValue();
component.set("v.option", allValues);
}
else if (state === "ERROR") {
var errors = response.getError();
if (errors) {
if (errors[0] && errors[0].message) {
console.log("Error message: " +
errors[0].message);
}
}
else {
console.log("Unknown Error");
}
}
});
$A.enqueueAction(action);
}
Controller:
#AuraEnabled
public static List<String> getObjectName(){
List<String> objects=new List<String>();
List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();
for(SObjectType sot:gd){
objects.add(sot.getDescribe().getName());
objects.sort();
}
return objects;
}
I just want to remove names from my list which starts with the skyvvasolution__
I have a file and user data that is being posted from Multipart/form data to a post method in my apicontroller class.
I am able to read the file without any problems but unable to read user data.
I tried couple of things like using model binding, passing the individual fields as a method parameter in the post method but i get: No MediaTypeFormatter is available to read an object of type 'FormDataCollection' from content with media type 'multipart/form-data'.
var provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
foreach (var item in provider.Contents)
{
var fieldName = item.Headers.ContentDisposition.Name.Trim('"');
if (item.Headers.ContentDisposition.FileName == null)
{
var data = await item.ReadAsStringAsync();
if (fieldname == "name")
{
Name = data;
}
else
{
fileContents = await item.ReadAsByteArrayAsync();
}
}
}
Thanks.
It seems to me the OP, was really close. This is some code that tries to clearly show how to get the form variables, as well as the file upload data.
First the ApiController:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class FormAndFileDataController : ApiController
{
private class FormItem
{
public FormItem() { }
public string name { get; set; }
public byte[] data { get; set; }
public string fileName { get; set; }
public string mediaType { get; set; }
public string value { get { return Encoding.Default.GetString(data); } }
public bool isAFileUpload { get { return !String.IsNullOrEmpty(fileName); } }
}
/// <summary>
/// An ApiController to access an AJAX form post.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <returns></returns>
public async Task<HttpResponseMessage> Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var formItems = new List<FormItem>();
// Scan the Multiple Parts
foreach (HttpContent contentPart in provider.Contents)
{
var formItem = new FormItem();
var contentDisposition = contentPart.Headers.ContentDisposition;
formItem.name = contentDisposition.Name.Trim('"');
formItem.data = await contentPart.ReadAsByteArrayAsync();
formItem.fileName = String.IsNullOrEmpty(contentDisposition.FileName) ? "" : contentDisposition.FileName.Trim('"');
formItem.mediaType = contentPart.Headers.ContentType == null ? "" : String.IsNullOrEmpty(contentPart.Headers.ContentType.MediaType) ? "" : contentPart.Headers.ContentType.MediaType;
formItems.Add(formItem);
}
// We now have a list of all the distinct items from the *form post*.
// We can now decide to do something with the items.
foreach (FormItem formItemToProcess in formItems)
{
if (formItemToProcess.isAFileUpload)
{
// This is a file. Do something with the file. Write it to disk, store in a database. Whatever you want to do.
// The name the client used to identify the *file* input element of the *form post* is stored in formItem.name.
// The *suggested* file name from the client is stored in formItemToProcess.fileName
// The media type (MimeType) of file (as far as the client knew) if available, is stored in formItemToProcess.mediaType
// The file data is stored in the byte[] formItemToProcess.data
}
else
{
// This is a form variable. Do something with the form variable. Update a DB table, whatever you want to do.
// The name the client used to identify the input element of the *form post* is stored in formItem.name.
// The value the client input element is stored in formItem.value.
}
}
return Request.CreateResponse(HttpStatusCode.OK);
}
}
}
and the MVC View to test it:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript">
var hiddenForm, hiddenFile;
function initialize() {
// Use a hidden file element so we can control the UI
// of the file selection interface. The built in browser
// UI is not localizable to different languages.
hiddenFile = document.createElement("input");
hiddenFile.setAttribute("type", "file");
hiddenFile.setAttribute("style", "display: none;");
// We don't need the form really, but it makes it easy to
// reset the selection.
hiddenForm = document.createElement("form");
hiddenForm.appendChild(hiddenFile);
hiddenFile.onchange = function () {
var elementToUpdate = document.getElementById("fileNameToUpload");
var filesToUpload = hiddenFile.files;
var fileToUpload = filesToUpload[0];
elementToUpdate.value = fileToUpload.name;
}
document.body.appendChild(hiddenForm);
}
function chooseFile() {
hiddenFile.click();
}
function clearFile() {
var elementToUpdate = document.getElementById("fileNameToUpload");
elementToUpdate.value = "";
hiddenForm.reset();
}
function testAJAXUpload() {
// We are going to use the FormData object and jQuery
// to do our post test.
var formToPost = new FormData();
var formVariableNameElement = document.getElementById("variableNameToUpload");
var formVariableValueElement = document.getElementById("variableValueToUpload");
var formVariableName = formVariableNameElement.value || "formVar1";
var formVariableValue = formVariableValueElement.value || "Form Value 1";
var filesToUpload = hiddenFile.files;
var fileToUpload = filesToUpload[0];
formToPost.append(formVariableName,formVariableValue)
formToPost.append("fileUpload", fileToUpload);
// Call the Server.
$.ajax({
url: '#Url.HttpRouteUrl("DefaultApi", new { controller = "FormAndFileData" })',
type: 'POST',
contentType: false,
processData: false,
data: formToPost,
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed: [" + textStatus + "]");
},
success: function (data, textStatus, jqXHR) {
alert("Success.");
}
});
}
</script>
</head>
<body>
<input id="variableNameToUpload" type="text" placeholder="Form Variable: Name" />
<br />
<input id="variableValueToUpload" type="text" placeholder="Form Variable: Value" />
<br />
<input id="fileNameToUpload" type="text" placeholder="Select A File..." /><button onclick="chooseFile()">Select File</button><button onclick="clearFile()">Reset</button>
<br />
<button onclick="testAJAXUpload()">Test AJAX Upload</button>
<script type="text/javascript">
initialize();
</script>
</body>
</html>
I had considered adding this to your other post per your comment, but (as you also decided), it is a separate question.
public async Task<HttpResponseMessage> Post()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
try
{
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = await Request.Content.ReadAsMultipartAsync(new MultipartFormDataStreamProvider(root));
// file data
foreach (MultipartFileData file in provider.FileData)
{
using (var ms = new MemoryStream())
{
var diskFile = new FileStream(file.LocalFileName, FileMode.Open);
await diskFile.CopyToAsync(ms);
var byteArray = ms.ToArray();
}
}
// form data
foreach (var key in provider.FormData.AllKeys)
{
var values = provider.FormData.GetValues(key);
if (values != null)
{
foreach (var value in values)
{
Console.WriteLine(value);
}
}
}
return Request.CreateResponse(HttpStatusCode.Created);
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
How to pass the selected value of a drop down list from view to controller after postback. As i'm new to the MVC architecture any help will be greatly appreciated. Thanks in advance.
I need to filter data based on the values of dropdown list. But when i move to the next page of pagedlist then all my dropdown list's value is set to default value.
Controller
public ActionResult ViewDataOfDatabase(string sortorder, string currentFilter, string searchString, int? page,FormCollection collection)
{
CCIRepository _repository = CCIRepository.CreateRepository();
AirtelManagementModel _Airtelmodel = new AirtelManagementModel();
IEnumerable<CityListClass> CityList = _repository.GetCities();
IEnumerable<SelectListItem> CityNames = from c in CityList
select new SelectListItem()
{
Value = c.CityName.ToString(),
Text = c.CityName.ToString(),
Selected = c.CityName == Request["CityNames"],
};
ViewBag.CityList = CityNames;
IEnumerable<clsYearOfDate> SelectList = GetYears();
//IEnumerable<MonthListClass> SelectMonthList = GetMonths(YearId);
IEnumerable<SelectListItem> Yearitems = (from v in SelectList
select new SelectListItem()
{
Value = v.YearSelectedId.ToString(),
Text = v.YearOfDate.ToString(),
Selected = v.YearOfDate == Request["Yearitems"],
});
ViewBag.SelectList = Yearitems;
int DateId=0;
string CityName = string.Empty;
try
{
int SelectedYear = Convert.ToInt16(collection["Yearitems"].ToString());
int SelectedMonth = Convert.ToInt16(collection["MonthItems"].ToString());
CityName = collection["CityNames"].ToString();
DateId = _repository.GetImportDateId(SelectedYear, SelectedMonth);
ViewBag.SelectedYear = SelectedYear;
ViewBag.SelectedMonth = SelectedMonth;
ViewBag.SelectedCity = CityName;
}
catch(NullReferenceException Ex)
{
Console.WriteLine(Ex);
}
//IEnumerable<SelectListItem> MonthItems = (from m in SelectMonthList
// select new SelectListItem()
// {
// Value = m.MonthSelectedId.ToString(),
// Text = m.MonthName,
// });
//ViewBag.SelectMonthList = MonthItems;
IEnumerable<SelectListItem> MonthItems = Enumerable.Empty<SelectListItem>();
ViewBag.SelectMonthList = MonthItems;
List<AirtelManagementModel> list = ViewDetails();
ViewBag.CurrentSort = sortorder;
ViewBag.PhoneSortParm = String.IsNullOrEmpty(sortorder) ? "Phone_desc" : "";
if (searchString != null )
{
page = 1;
}
else
{
searchString = currentFilter;
}
//if(searchString!=null)
//{
ViewBag.CurrentFilter = searchString;
var airteldetails = from _model in list
select _model;
if(!String.IsNullOrEmpty(searchString) && DateId!=0 && !String.IsNullOrEmpty(CityName))
{
airteldetails = _repository.FilterAirtelDetails(searchString, DateId, CityName);
int PageSize = 5;
int PageNumber = (page ?? 1);
return View(airteldetails.ToPagedList(PageNumber, PageSize));
}
//airteldetails=airteldetails.OrderByDescending(A=>A.AirtelNumber);
int pageSize = 5;
int pageNumber = (page ?? 1);
//return View(airteldetails.ToList());
return View(airteldetails.ToPagedList(pageNumber, pageSize));
}
View
<h2 style="text-align:center">AirtelDetails</h2>
#using (Html.BeginForm("ViewDataOfDatabase", "AirtelManagement",FormMethod.Post))
{
<h3>Search by PhoneNumber:#Html.TextBox("SearchString",ViewBag.CurrentFilter as string)</h3>
<p><h3>Year:#Html.DropDownList("Yearitems",(IEnumerable<SelectListItem>)ViewBag.SelectList, "Select Year")</h3>
<h3>Month:#Html.DropDownList("MonthItems", (IEnumerable<SelectListItem>)ViewBag.SelectMonthList, "Select Month")</h3>
<h3>City: #Html.DropDownList("CityNames", (IEnumerable<SelectListItem>)ViewBag.CityList, "Select City")</h3></p>
<p><input type="submit" value="Search" /></p>
<script>
$(document).ready(function () {
$("#Yearitems").change(function () {
//debugger;
//alert($("#Yearitems>option:selected").attr("Value"));
$.ajax({
type: "Post",
url: '#Url.Action("GetMonths","AirtelManagement")',
data: { YearId: $("#Yearitems>option:selected").attr("Value") },
datatype: "Json",
success: function (data) {
//debugger;
$("#MonthItems").html("");
$.each(data, function (index, item) {
$("#MonthItems").append(new Option(item.MonthName, item.MonthSelectedId));
});
},
error: function () {
alert("Select Year");
}
});
});
});
</script>
}
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("ViewDataOfDatabase", "AirtelManagement", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
Hy, I'm stuck with this error message and I can not find an solution.
I get this message error in the Knockout JavaScript library v2.2.0:
Unhandled exception at line 1053, column 5 in
localhost:port/Scripts/knockout-2.2.0.debug.js 0x800a138f -
Microsoft JScript runtime error: Invalid operand to 'in': Object
expected If there is a handler for this exception, the program may be
safely continued.
It stops at this line of code in knockout-2.2.0.debug.js
if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
I use this WebApi:
public class ProductsController : ApiController
{
IEnumerable<Product> products = new List<Product>()
{
new Product { Id = 1, Name = "Tomato_Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts(){
return products.AsEnumerable(); }
The scripts that I use are in a header section
#section Testscripts
{
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/knockout-2.2.0.debug.js"></script>
}
And the Knockout code in the footer default script section
#section scripts
{
<script type="text/javascript">
var apiUrl = '#Url.RouteUrl("DefaultApi", new { httproute = "", controller = "products" })';
function Product(data) {
this.Id = ko.observable(data.Id);
this.Name = ko.observable(data.Name);
this.Price = ko.observableArray(data.Price);
this.Category = ko.observable(data.Category);
}
function ProductViewModel() {
var self = this;
self.myproducts = ko.observableArray([]);
$.getJSON(apiUrl, function (allData) {
var mappedProducts = $.map(allData, function (item) { return new Product(item) });
self.myproducts(mappedProducts);
});
};
ko.applyBindings(new ProductViewModel);
}
and show the data in body:
<ul data-bind="foreach: myproducts">
<li>
<input data-bind="value: Id" />
<input data-bind="value: Name" />
<input data-bind="value: Category" />
<input data-bind="value: Price" />
</li>
</ul>
The bug is in your Product function.
You want to create an ko.observableArray from data.Price which is a decimal value and not an array of values, which results in this not so nice exception.
Change to ko.observable and it should work:
function Product(data) {
this.Id = ko.observable(data.Id);
this.Name = ko.observable(data.Name);
this.Price = ko.observable(data.Price);
this.Category = ko.observable(data.Category);
}
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;
....
}