500 error in Ajax Get - ajax

I'm trying to send a dropdownlists selected value to controller and retrieve json data back.
When I debug, parameter gets to controller nicely, values are retrieved nicely but after return part on console it says
"Failed to load resource: the server responded with a status of 500 (Internal Server Error)`"
This is my controller action: (in WebContentsController)
[HttpGet]
public JsonResult GetWebContentTypeDetails (int id)
{
var details = db.WebContentTypeDetail.Where(x=>x.WebContentTypeID == id).ToList();
return Json(details, JsonRequestBehavior.AllowGet);
}
this is JS part (printing it to console for testing)
$(document).ready(function () {
$("#WebContentTypeID").change(function () {
var ChangedID = $('#WebContentTypeID option:selected').val();
alert(ChangedID);
$.getJSON('/webcontents/GetWebContentTypeDetails/' + ChangedID, function (data) {
console.log(data);
})
});
});
EDIT:
WebContentTypeDetail model
public partial class WebContentTypeDetail
{
public int WebContentTypeDetailID { get; set; }
public int WebContentTypeID { get; set; }
public string DetailKey { get; set; }
public string Description { get; set; }
public Nullable<short> Rank { get; set; }
public virtual WebContentType WebContentType { get; set; }
}
WebContentType model
public partial class WebContentType
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public WebContentType()
{
this.WebContent = new HashSet<WebContent>();
this.WebContentTypeDetail = new HashSet<WebContentTypeDetail>();
}
public int WebContentTypeID { get; set; }
public string DisplayName { get; set; }
public string CreatedByUserID { get; set; }
public System.DateTime CreateDate { get; set; }
public string LastEditedByUserID { get; set; }
public Nullable<System.DateTime> LastEditDate { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<WebContent> WebContent { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<WebContentTypeDetail> WebContentTypeDetail { get; set; }
}

You cannot directly return a entity list from context query result, because they are not serializable in most of cases, especially in your case: entities got a loop references.
you have 2 options:
var details = db.WebContentTypeDetail.Where(x=>x.WebContentTypeID == id)
map your result to anonymous object list:
return Json(details.select(x=>new {
//you data structure
}).ToList(), JsonRequestBehavior.AllowGet);
create your view model and mark it [Serializable], then return necessary data to client:
return Json(details.select(x=>new YourViewModel {
//you data structure
}).ToList(), JsonRequestBehavior.AllowGet);

Try this:
$(document).ready(function () {
$("#WebContentTypeID").change(function () {
var ChangedID = $('#WebContentTypeID option:selected').val();
alert(ChangedID);
$.getJSON('/webcontents/GetWebContentTypeDetails?id=' + ChangedID, function (data) {
console.log(data);
})
});
});
As parameter id should be passed as querystring. And if you're using mvc then url should be passed in #url.action so it must be
$(document).ready(function () {
$("#WebContentTypeID").change(function () {
var ChangedID = $('#WebContentTypeID option:selected').val();
alert(ChangedID);
var URL = #Url.Action("_GetWebContentTypeDetails", "webcontents");
$.getJSON(URL + '?id=' + ChangedID, function (data) {
console.log(data);
})
});
});

Related

How to convert formcollection to model ins ASP.NET MVC

I have a model class called ClientPackage and in my controller action method i receive a FormCollection from an ajax post call that i would like to convert it to the model class ClientPackage.
public class ClientPackage
{
public int DemandeId { get; set; }
public string NumeroRequette { get; set; }
public string NumeroModification { get; set; }
public int CasId { get; set; }
public string NumeroDossier { get; set; }
public string NomPatient { get; set; }
public string PrenomPatient { get; set; }
public string NiveauPriorite { get; set; }
public int NiveauPrioriteId { get; set; }
public Unite UniteDepart { get; set; }
public Unite UniteDestination { get; set; }
public Demandeur DemandeurDepart { get; set; }
public Demandeur DemandeurDestination { get; set; }
public ConditionTransport ConditionTransport { get; set; }
public Transport Transport { get; set; }
}
[HttpPost]
public string AjaxCall(FormCollection formData)
{
ClientPackage package = (ClientPackage)formData; //exception error
}
I would appriciate any help
Instead of trying to convert you can use the FromForm attribute and receive your model as a parameter.
[HttpPost]
public ActionResult CreateClientPackage([FromForm] ClientPackage clientPackage)
{
...
}
Here is how I post models with ajax.
<script>
function PostForm() {
var model = $('#your_form_id').serialize();
$.ajax({
url: '/YourController/AjaxCall',
type: 'POST',
data: model,
success: function (data) {
},
error: function (request, error) {
console.log("Request: " + JSON.stringify(request));
}
});
}
</script>
and in your controller.
[HttpPost]
public string AjaxCall(ClientPackage model)
{
//no need to cast the model to a ClientPackage
//ASP.NET mvc will do it for you as long as you send a serialized form that represents a ClientPackage object
}
Hope this helps!

Posting a complex object through ajax along with other simple types

I know that this question has been asked like a hundred times, but I can't figure it out.
I have an ajax call like
function saveBox()
{
var postModel = createBoxPostModel();
showLoader();
$.ajax({
async: true,
type: 'post',
url: '#(Url.BuildAction<IncomingGoodsVerificationController>(x => x.SaveWorkUnitForBox(null, null, null)))',
data: { jsonPostModel: postModel, boxItemKey: boxItemKey, itemKey: itemKey },
success: function (data, status) {
...
},
error: function (jqXHR, textStatus, errorThrown) {
hideLoader();
displayErrorMessagePopup('Error in saving box! ', errorThrown, 'error-msgs');
}
});
}
and the controller method is like
[HttpPost]
public JsonResult SaveWorkUnitForBox(NewWorkUnitBoxModel postModel, string boxItemKey, string itemKey)
{
....
}
The NewWorkUnitBoxModel is
public class NewWorkUnitBoxModel
{
public NewWorkUnitBoxModel();
public string AlternativeWorkUnitNumer { get; set; }
public string Barcode { get; set; }
public int ChooseType { get; set; }
public decimal? GrossWeight { get; set; }
public long IdCompany { get; set; }
public long? IdPackagingType { get; set; }
public long? IdWorkUnitSubType { get; set; }
public decimal? NetWeight { get; set; }
public string Tone { get; set; }
public decimal? Volume { get; set; }
public long? WorkUnitNumber2 { get; set; }
}
and yet when the controller action is called is either null or the object has no value for each of its properties.
I tried several ways:
data: { jsonPostModel: postModel, boxItemKey: boxItemKey, itemKey: itemKey }
data: { jsonPostModel: JSON.stringify(postModel), boxItemKey: boxItemKey, itemKey: itemKey }
Putting all action parameters inside a request class
None of these worked. Client-side the model is loaded correctly, and by using ModelBinders I also looked inside the HtmlRequest and data had arrived on the server. I only solved with changing the type to a string and deserialize it inside the action.
How can I make it automatically deserialize the model?

Bar Chart of ChartJS does not Render

I am having trouble displaying bar chart from my ASP.NET-MVC-5 application. I witnessed the JSON comes out correctly (sample is applied below), and as per documentation I had included all, yet the output comes as below:
HTML:
<div class="jumbotron">
<h1>Another Chart</h1>
<canvas id="barChartLoc" width="600" height="400"></canvas>
</div>
This is the Script which calls the Controller, which returns a JSON:
<script type="text/javascript">
function chartFYRevenue() {
$.ajax({
url: '#Url.Action("GetLast5FYRevenueAnalysis", "Utility")',
cache: true
})
.done(function (data) {
var mybarChartLoc = new Chart(document.getElementById("barChartLoc").getContext("2d")).Bar(data);
})
.fail(function () {
alert("Ajax failed to fetch data");
});
}
$(document).ready(function () {
//auto load on page load
chartFYRevenue();
});
</script>
This is the Controller which returns a JSON. I have tested this and things are fine here as well:
public JsonResult GetLast5FYRevenueAnalysis()
{
Models.Chart.BarChartDBContext chartDB = new Models.Chart.BarChartDBContext();
return Json(chartDB.Test, JsonRequestBehavior.AllowGet);
}
This is the Modeler class where I build the Chart Data dynamically:
public class ChartDataSets
{
public string label { get; set; }
public string fillColor { get; set; }
public string highlightFill { get; set; }
public string highlightStroke { get; set; }
public string strokeColor { get; set; }
public string data { get; set; }
}
public class BarChartModel
{
public string labels { get; set; }
public List<ChartDataSets> datasets { get; set; }
}
public class BarChartDBContext : Models.DBHelper.DBHelperClass
{
public BarChartModel GetLast5FInancialYearRevenue
{
get { return getLast5FinancialYearRevenue(); }
}
public BarChartModel Test
{
get { return test(); }
}
private BarChartModel test()
{
List<ChartDataSets> _datasets = new List<ChartDataSets>();
BarChartModel _barChartModel = null;
_datasets.Add(new ChartDataSets()
{
data = string.Format("[{0}]", "10,5,25,35"),
fillColor = "rgba(220,220,220,0.5)",
highlightFill = "rgba(220,220,220,0.75)",
highlightStroke = "rgba(220,220,220,1)",
strokeColor = "rgba(220,220,220,0.8)",
label = "s1"
});
_barChartModel = new BarChartModel();
_barChartModel.labels = string.Format("[{0}]", "c1,c2,c3,c4");
_barChartModel.datasets = _datasets;
return _barChartModel;
}
}
JSON Data Sample:
{
"labels": "[c1,c2,c3,c4]",
"datasets": [
{
"label": "s1",
"fillColor": "rgba(220,220,220,0.5)",
"highlightFill": "rgba(220,220,220,0.75)",
"highlightStroke": "rgba(220,220,220,1)",
"strokeColor": "rgba(220,220,220,0.8)",
"data": "[10,5,25,35]"
}
]
}
Update:
I modified my ChartDataSet and BarChartModel Class to the following:
public class ChartDataSets
{
public string label { get; set; }
public string fillColor { get; set; }
public string highlightFill { get; set; }
public string highlightStroke { get; set; }
public string strokeColor { get; set; }
public string[] data { get; set; }
}
public class BarChartModel
{
public string[] labels { get; set; }
public List<ChartDataSets> datasets { get; set; }
}
Your JSON data generated is incorrect. The right output should be
"{
"labels": ["c1","c2","c3","c4"],
"datasets": [
{
"label":"s1",
"fillColor":"rgba(220,220,220,0.5)",
"highlightFill":"rgba(220,220,220,0.75)",
"highlightStroke":"rgba(220,220,220,1)",
"strokeColor":"rgba(220,220,220,0.8)",
"data":[10,5,25,35]
}
]
}"

Ajax post model to controller action

In mvc4 i am trying to Post model data from view to controller using Jquery Ajax but don't now what's wrong with this code can any one help me in this matter.
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#save").click(function () {
$("#content").html("<b>Please Wait...</b>");
var dataObject = {
empid: 1,
EmployeeName: "rizwan",
Address: "lahore",
Country: "pakistan",
Salary: "35000.00",
DepartmentName: "Field"
}
$.ajax({
type: "POST",
url: "/Home/Index",
data: dataObject,
success: function (data)
{
$("#empname").val(''),
$("#empadd").val(''),
$("#empcountry").val(''),
$("#empsalary").val(''),
$("#empdeptname").val(''),
$("#content").html("<div class='success'>"+data+"</div>")
},
error: function (ehr)
{
$("#content").html("<div class='failed'>Error! Please try again</div>");
},
})
});
});
</script>
This is my controller action code who just receive the value of object and save into database
Problem is that i failed to receive values at controller action side.
Please help me.....
[HttpPost]
public ActionResult Index(userview dataObject)
{
department dept = new department();
employee emp = new employee();
string message = "";
try
{
emp.employeeName = dataObject.EmployeeName;
emp.address = dataObject.Address;
emp.country = dataObject.Country;
emp.salary = dataObject.Salary;
dept.departmentName = dataObject.DepartmentName;
db.employees.Add(emp);
db.departments.Add(dept);
db.SaveChanges();
}
catch(Exception ex)
{
message = "Error! Please try again";
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
ViewBag.message = message;
return View();
}
This is my model class
public class userview
{
public int empId { get; set; }
public string EmployeeName { get; set; }
public string Address { get; set; }
public string Country { get; set; }
public decimal Salary { get; set; }
public string DepartmentName { get; set; }
}
Try using JSON.stringify
$.ajax({
type: "POST",
url: "/Home/Index",
data: JSON.stringify(dataObject), //Here is the change
success: function (data)
{
$("#empname").val(''),
$("#empadd").val(''),
$("#empcountry").val(''),
$("#empsalary").val(''),
$("#empdeptname").val(''),
$("#content").html("<div class='success'>"+data+"</div>")
},
error: function (ehr)
{
$("#content").html("<div class='failed'>Error! Please try again</div>");
},
})
You can implement BindModel yourself! get the json string and deserialize to your entity.
public class JsonBinder<T> : System.Web.Mvc.IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
using (var reader = new System.IO.StreamReader(controllerContext.HttpContext.Request.InputStream))
{
//set stream position 0, maybe previous action already read the stream.
controllerContext.HttpContext.Request.InputStream.Position = 0;
string json = reader.ReadToEnd();
if (string.IsNullOrEmpty(json) == false)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
object jsonData = serializer.DeserializeObject(json);
return serializer.Deserialize<T>(json);
}
else
{
return null;
}
}
}
}
and set the JsonBinder to the post method like
[HttpPost]
public ActionResult Index([ModelBinder(typeof(JsonBinder<userview>))] userview dataObject)
{
}
the other solution
I found that you could set DataContract to the class of Model, and set DataMember to the Properties of the class.
edit the class like this
[DataContract]
public class userview
{
[DataMember]
public int empId { get; set; }
[DataMember]
public string EmployeeName { get; set; }
[DataMember]
public string Address { get; set; }
[DataMember]
public string Country { get; set; }
[DataMember]
public decimal Salary { get; set; }
[DataMember]
public string DepartmentName { get; set; }
}
and you should add library reference "System.Runtime.Serialization"
Hope it works for you.

Kendo Tree View doesn't load properly

I wanna create a kendo ui tree view with remote data source in Asp.net mvc4. I'm having a problem with knowledge about kendo. I've tried those examples in kendo website .
But i couldn't even get those images to the treeView.
About the project : This project is to create a TreeView menu for load web forms. Each web form can be taken as an formObject. That objects has following attributes
name
id
List of child objects (List childs)
Here is my Codes on the Controller
public class HomeController : Controller
{
ObjectService service = new ObjectService();
private int cky = 11;
private int usrky=28;
public ActionResult Index()
{
return View();
}
public ActionResult GetAllMenu(int prntKy = 1)// initially the parent key is = 1
{
List<ObjectModel> objects = new List<ObjectModel>();
objects = service.GetObjectsByPrntKy(prntKy, cky, usrky);//get all parent nodes
List<TreeViewModel> tree = new List<TreeViewModel>();
if (objects != null)
{
foreach (ObjectModel model in objects)//for each parent node
{
TreeViewModel treeObj = new TreeViewModel();
treeObj.id = model.ObjKy;
treeObj.name = model.ObjNm;
treeObj.childrens = GetChileByPrntObjKy(model.ObjKy);
tree.Add(treeObj);
}
}
return Json(tree, JsonRequestBehavior.AllowGet);
}
private List<TreeViewModel> GetChileByPrntObjKy(int prntKy)// method to get child nodes
{
List<TreeViewModel> tree = new List<TreeViewModel>();
List<ObjectModel> Objects = new List<ObjectModel>();
Objects = service.GetAllObjects();
foreach (ObjectModel model in Objects)
{
TreeViewModel treeObj = new TreeViewModel();
if (model.PrntObjKy == prntKy)
{
treeObj.id = model.ObjKy;
treeObj.name = model.ObjNm;
treeObj.childrens = GetChileByPrntObjKy(model.ObjKy);
tree.Add(treeObj);
}
}
return tree;
}
}
Here is the model
public class TreeViewModel
{
public int pid { get; set; }
public int id { get; set; }
public string name { get; set; }
public List<TreeViewModel> childrens { get; set; }
}
public class ObjectModel
{
public long UsrObjPrmsnKy { get; set; }
public long UsrKy { get; set; }
public int ObjKy { get; set; }
public string ObjCd { get; set; }
public string ObjNm { get; set; }
public string ObjCaptn { get; set; }
public bool isPrntObj { get; set; }
public Nullable<int> PrntObjKy { get; set; }
public int CallObjKy { get; set; }
public string ObjPath { get; set; }
public bool isAlwAcs { get; set; }
public bool isAlwAdd { get; set; }
public bool isAlwUpdate { get; set; }
public bool isAlwDel { get; set; }
public bool isAlwApr { get; set; }
}
and here is the View
<div id="treeview">
</div>
<script type="text/javascript">
$(document).ready(function () {
LoadTreeView(1);
});
function LoadTreeView(prntKy)
{
var key = prntKy;
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: '#Url.Content("~/Home/GetAllMenu")',
data:{'prntKy':key},
dataType: "json"
}
},
schema: {
model: {
id: "id",
hasChildren: "childrens",
name: "name"
}
}
});
$("#treeview").kendoTreeView({
dataSource: homogeneous,
select: onSelectTree,
dataTextField: "name",
dataValueField: "id",
});
}
function onSelectTree(e) {
var data = $('#treeview').data('kendoTreeView').dataItem(e.node);
alert(data.id);
LoadTreeView(data.id);
}
</script>
I have uploaded the results images too. Please help me.
Your treeview isn't properly configured. You seem to be reinitializing it every time a node is selected which is redundant. I suggest you check the remote binding demo which implements a very similar case to yours. Here is how the treeview declaration looks:
var serviceRoot = "http://demos.kendoui.com/service";
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot + "/Employees",
dataType: "jsonp" // you don't need "json" for your case
}
},
schema: {
model: {
id: "EmployeeId",
hasChildren: "HasEmployees"
}
}
});
$("#treeview").kendoTreeView({
dataSource: homogeneous,
dataTextField: "FullName"
});
In this demo the treeview will ask the data source to load a new level of nodes when a parent node is expanded. For example when the user expands the root node in that demo the data source makes request to http://demos.kendoui.com/service/Employees?EmployeeId=2 which means "return the children of the node whose EmployeeID is equal to 2". Why "EmployeeId"? Because this is what the "id" of the data source model is:
schema: {
model: {
id: "EmployeeId",
hasChildren: "HasEmployees"
}
}

Resources