String instead of data - asp.net-mvc

I'm trying to get data from the controller
something like this:
public IEnumerable<Custom> Search(string searchText = "")
{
return new[] { new Custom { Name = "a", Id = 1 }, new Custom { Name = "b", Id = 1 }, new Custom { Name = "c", Id = 3 } };
}
But angular gives me this
m
u
s
i
c
p
o
r
t
a
l
.
C
o
n
t
r
o
l
l
e
r
s
.
C
u
s
t
o
m
[
]
I tried add http.headers but nothing.
My code:
var musicportal = angular.module('musicportal', []);
musicportal.controller('SearchController', ['$scope', '$http', function ($scope, $http) {
$scope.answer = "awesome";
$scope.search = function (text) {
$scope.answer = text;
$scope.pms = [];
$http.post('/Home/Search', { searchText: text }).
success(function (data, status, headers, config) {
$scope.pms = data;
});
$scope.searchText = "";
}
}]);

You should return data as json e.g.
public ActionResult Search(string searchText = "")
{
return Json(new { Foo = "Hello" }, JsonRequestBehavior.AllowGet);
}
$http.post('/Home/Search', { searchText: text }).
success(function (data, status, headers, config) {
$scope.pms = data.Foo;
});
Now, in your case, you have a list, so you need to convert that into JSON. You can do that in ASP.NET MVC using JsonSerializer e.g.
public ActionResult Search(string searchText = "")
{
string json = "";
var items = new[] { new Custom { Name = "a", Id = 1 }, new Custom { Name = "b", Id = 1 }, new Custom { Name = "c", Id = 3 } };
using (var writer = new StringWriter())
using (var jsonWriter = new JsonTextWriter(writer))
{
serializer.Serialize(jsonWriter, items);
json = writer.ToString();
}
return Json(json, JsonRequestBehavior.AllowGet);
}
$http.post('/Home/Search', { searchText: text }).
success(function (data, status, headers, config) {
$scope.pms = JSON.Parse(data);
});
You may need to play about with this code, it's not perfect first time, but hopefully it will give you a head start.

Related

How to convert array to send as query string?

In my view, I have checkboxes and some data displayed and button on each row to approve or reject requests put up.
I want to send my integer array to my action method but this cannot be done by just sending it to action query parameters and it would be like the picture below:
public int[] Ids
{
get { return new int[] { 1, 2, 3 }; }
set {}
}
public ActionResult Approval([ModelBinder(typeof(IntArrayModelBinder))] int[] ids)
{
...
return View(...);
}
#Html.ActionLink("Approve", "Approval", new {id = item.Ids, approvalAction = "approve"})
How do I implement the checkboxes to be checked and hover of the approve/reject actionlink will show the url with ../ids=1&ids=2&ids=3 instead of System.Int32[]?
Option 1: Send your array as a comma-separated string and then split them in your action like this :
#Html.ActionLink("Approve", "Approval", new { id = string.Join("," , Ids), approvalAction = "approve" } )
your action :
public ActionResult YourAction(string id , string approvalAction)
{
var ids = id.Split(',');
//rest of your action method business
}
Option 2:
another way to achieve your exactly url is to create your URL like this :
var baseUrl = Url.Action("YourAction", "YourController", null, Request.Url.Scheme);
var uriBuilder = new UriBuilder(baseUrl);
uriBuilder.Query = string.Join("&", Ids.Select(x => "ids=" + x));
string url = uriBuilder.ToString();
url += "&approvalAction=approve"
and your action would be like this :
public ActionResult YourAction(int[] ids , string approvalAction)
{}
<script>
function multiSelect(selectedArray, action) {
if (selectedArray[0] === undefined) {
alert("You have not selected any employee");
}
//example url
//..?ids=1&ids=2&ids=3&aprovalAction=approve
else {
var param = "";
var currUrl = "";
var idUrl = "";
idUrl = "ids=" + selectedArray[0];
for (var i = 1; i < selectedArray.length; ++i) {
idUrl += "&ids=" + selectedArray[i];
}
switch (action) {
case "Approve":
param = "approve";
break;
case "Reject":
param = "reject";
break;
}
currUrl = "approvalAction=" + param;
window.location.href = "?" + idUrl + "&" + currUrl;
}
}
</script>
<script>
$('#MultiApproveBtn').click(function () {
var selected = $('input[type=checkbox]:checked').map(function (_, el) {
return $(el).val();
}).get();
var x = document.getElementById("MultiApproveBtn").value;
//alert(selected);
multiSelect(selected, x);
})
</script>
<script>
$('#MultiRejectBtn').click(function () {
var selected = $('input[type=checkbox]:checked').map(function (_, el) {
return $(el).val();
}).get();
var x = document.getElementById("MultiRejectBtn").value;
//alert(selected);
multiSelect(selected, x);
})
</script>

How to reload session values

I am sending data from view to controller using ajax , modelID , catId etc and searching data from database against these parameters, but first time load session values but after that if i change its value cant not load session values.
$("#ModelID").change(function () {
var Cat = $("#Cat").val();
var subcat = $("#CatID").val();
if (Cat != "" & subcat != "") {
$("#modalvalag").modal("show");
$.ajax({
type: 'post',
url: '/Inventory/CatSubCatAgainstModal',
data: {
Cat: $("#Cat").val(),
SubCat: $("#CatID").val(),
ModelID: $("#ModelID").val()
},
success: function (response) {
$('#noo').html(response);
}
});
}
else {
alert("Please select Category Or sub category to complete this process");
}
return false
});
Here is controller code:
public ActionResult CatSubCatAgainstModal(int Cat = 0, int SubCat = 0 , int ModelID = 0)
{
// var dta = db.ItemsCatSubCats.Where(m => m.CatID == CatID & m.SubCatID == SubCatID).FirstOrDefault();
//Session["ItemName"] = dta.Category.Catgory + "|" + dta.SubCategory.SubCat;
Session["CatID"] = Cat;
Session["SubCat"] = SubCat;
Session["ModelID"] = ModelID;
var data = db.ItemAttributes.Where(m => m.CatID == Cat & m.SubCatID == SubCat & m.ModelID == ModelID).ToList();
int c = 0;
foreach(var itm in data){
Session["value"+c] = itm.AttributeValue;
c++;
}
return RedirectToAction("AttributListForValue");
}

Ajax Not Working on Edit Method

I have an ajax method for a cascading drop down list, similar to country - state drop down list. It works fine on Create method, but I can't get it to work on Edit method. I get this error on Edit:
POST http://localhost/Submissions/Edit/SomeAJAXMethod 500 (Internal Server Error)
There is an extra /Edit in the path that makes it not work. It works just fine on Create. I tried to add ~/. I get these errors on Create and Edit method:
POST http://localhost/Submissions/Edit/~/SomeAJAXMethod 404 (Not Found)
I tried to add ../. I get this error on Create, works fine on Edit:
POST http://localhost/SomeAJAXMethod 404 (Not Found)
How do I make it work on both Create and Edit?
Below is my controller.
//
// GET: /Submissions/Create
public ActionResult Create()
{
ViewBag.ActivityRejectCodeId = GetRejectCodesByActivity(0);
ViewBag.Activities = GetActivities();
ViewBag.Workstations = GetWorkstationsByActivity(0);
ViewBag.Platforms = GetPlatformsByWorkstation(0, 0);
ViewBag.Parts = GetPartsByPlatform(0, 0, 0);
ViewBag.StatusId = new SelectList(db.Status, "Id", "Name");
ViewBag.Technicians = GetTechnicians(0);
ViewBag.Shifts = GetShiftsByTechnician(0, 0);
ViewBag.WorkOrderId = new SelectList(db.WorkOrders, "Id", "WO");
return View();
}
//
// POST: /Submissions/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(WorkOrderSubmission workordersubmission)
{
var activityId = Int32.Parse(Request.Form["ActivityId"]);
var workstationId = Int32.Parse(Request.Form["WorkstationId"]);
var platformId = Int32.Parse(Request.Form["PlatformId"]);
var partId = Int32.Parse(Request.Form["PartId"]);
var techId = Int32.Parse(Request.Form["TechnicianId"]);
var shiftId = Int32.Parse(Request.Form["ShiftId"]);
if (ModelState.IsValid)
{
// Get the PlatformStageId from the combination of (ActivityId, WorkstationId, PlatformId, PartId)
var rs = (from ps in db.PlatformStages
join wa in db.WorkstationActivities on ps.WorkstationActivityId equals wa.Id
join pp in db.PlatformParts on ps.PlatformPartId equals pp.Id
where ps.WorkstationActivity.ActivityId == activityId
&& ps.WorkstationActivity.WorkstationId == workstationId
&& ps.PlatformPart.PlatformId == platformId
&& ps.PlatformPart.PartId == partId
select new {
ps.Id
}).FirstOrDefault();
workordersubmission.PlatformStageId = rs.Id;
// Get TechnicianShiftId from the combination of (TechnicianId, ShiftId)
rs = (from ts in db.TechnicianShifts
where ts.TechnicianId == techId
&& ts.ShiftId == shiftId
select new
{
ts.Id
}).FirstOrDefault();
workordersubmission.TechnicianShiftId = rs.Id;
workordersubmission.SubmissionDate = DateTime.Now;
db.WorkOrderSubmissions.Add(workordersubmission);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ActivityRejectCodeId = new SelectList(db.ActivityRejectCodes, "Id", "RejectCodeId", workordersubmission.ActivityRejectCodeId);
ViewBag.Activities = GetActivities(activityId);
ViewBag.Workstations = GetWorkstationsByActivity(activityId, workstationId);
ViewBag.Platforms = GetPlatformsByWorkstation(activityId, workstationId, platformId);
ViewBag.Parts = GetPartsByPlatform(activityId, workstationId, platformId, partId);
ViewBag.StatusId = new SelectList(db.Status, "Id", "Name", workordersubmission.StatusId);
ViewBag.Technicians = GetTechnicians(techId);
ViewBag.Shifts = GetShiftsByTechnician(techId, shiftId);
ViewBag.WorkOrderId = new SelectList(db.WorkOrders, "Id", "WO", workordersubmission.WorkOrderId);
return View(workordersubmission);
}
//
// GET: /Submissions/Edit/5
public ActionResult Edit(int id = 0)
{
WorkOrderSubmission workordersubmission = db.WorkOrderSubmissions.Find(id);
if (workordersubmission == null)
{
return HttpNotFound();
}
var platformStageId = workordersubmission.PlatformStageId;
var technicianShiftId = workordersubmission.TechnicianShiftId;
// Get ActivityId, WorkstationId, PlatformId, PartId from PlatformStageId
var rs = (from ps in db.PlatformStages
join wa in db.WorkstationActivities on ps.WorkstationActivityId equals wa.Id
join pp in db.PlatformParts on ps.PlatformPartId equals pp.Id
where ps.Id == platformStageId
select new
{
ActivityId = wa.ActivityId,
WorkstationId = wa.WorkstationId,
PlatformId = pp.PlatformId,
PartId = pp.PartId
})
.FirstOrDefault();
ViewBag.Activities = GetActivities(rs.ActivityId);
ViewBag.Workstations = GetWorkstationsByActivity(rs.ActivityId, rs.WorkstationId);
ViewBag.Platforms = GetPlatformsByWorkstation(rs.ActivityId, rs.WorkstationId, rs.PlatformId);
ViewBag.Parts = GetPartsByPlatform(rs.ActivityId, rs.WorkstationId, rs.PlatformId, rs.PartId);
// Get TechnicianId, ShiftId from TechnicianShiftId
var rs2 = (from ts in db.TechnicianShifts
where ts.Id == technicianShiftId
select new //TechnicianShift
{
TechnicianId = ts.TechnicianId,
ShiftId = ts.ShiftId
})
.FirstOrDefault();
ViewBag.Technicians = GetTechnicians(rs2.TechnicianId);
ViewBag.Shifts = GetShiftsByTechnician(rs2.TechnicianId, rs2.ShiftId);
ViewBag.ActivityRejectCodeId = new SelectList(db.ActivityRejectCodes, "Id", "RejectCodeId", workordersubmission.ActivityRejectCodeId);
ViewBag.StatusId = new SelectList(db.Status, "Id", "Name", workordersubmission.StatusId);
ViewBag.WorkOrderId = new SelectList(db.WorkOrders, "Id", "WO", workordersubmission.WorkOrderId);
return View(workordersubmission);
}
//
// POST: /WorkorderSubmissions/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(WorkOrderSubmission workordersubmission)
{
if (ModelState.IsValid)
{
db.Entry(workordersubmission).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ActivityRejectCodeId = new SelectList(db.ActivityRejectCodes, "Id", "RejectCodeId", workordersubmission.ActivityRejectCodeId);
ViewBag.PlatformStageId = new SelectList(db.PlatformStages.OrderBy(p => p.Name), "Id", "Name", workordersubmission.PlatformStageId);
ViewBag.StatusId = new SelectList(db.Status, "Id", "Name", workordersubmission.StatusId);
ViewBag.TechnicianShiftId = new SelectList(db.TechnicianShifts, "Id", "Description", workordersubmission.TechnicianShiftId);
ViewBag.WorkOrderId = new SelectList(db.WorkOrders, "Id", "WO", workordersubmission.WorkOrderId);
return View(workordersubmission);
}
Below is the AJAX call:
$(function () {
// Code that triggers when there is a change in Activity drop down.
$('#ActivityId').change(function () {
var activityId = $(this).val();
var url = 'GetRejectCodesByActivityJson';
// Empty the Reject Code drop down list.
$('#ActivityRejectCodeId').empty();
// Empty the Workstation, Platform, Part drop downs.
$('#WorkstationId').empty();
$('#PlatformId').empty();
$('#PartId').empty();
$('.showhide-workstation').show();
// AJAX call that re-populate Reject Code drop down depending on the Activity selected.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: { activityId: activityId },
success: function (codes) {
$('#ActivityRejectCodeId').append('<option value=""></option>');
$.each(codes, function (i) {
$('#ActivityRejectCodeId').append('<option value = "' + codes[i].Value + '">' + codes[i].Text + '</option>')
});
},
error: function (ex) {
$('#ActivityRejectCodeId').append('<option value=""></option>');
}
}); // END $.ajax() on GetRejectCodesByActivityJson
url = 'GetWorkstationsByActivityJson';
// AJAX call that re-populate Workstation drop down depending on the Activity selected.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: { activityId: activityId },
success: function (codes) {
$('#WorkstationId').append('<option value=""></option>');
$.each(codes, function (i) {
$('#WorkstationId').append('<option value = "' + codes[i].Value + '">' + codes[i].Text + '</option>');
});
},
error: function (ex) {
$('#WorkstationId').append('<option value=""></option>');
}
}); // END $.ajax() on GetRejectCodesByActivityJson
}); // END $('#ActivityId').change()
// Code that triggers when there is a change in Workstation drop down.
$('#WorkstationId').change(function () {
var activityId = $('#ActivityId').val();
var workstationId = $(this).val();
var url = 'GetPlatformsByWorkstationJson';
// Empty the Platform, Part drop downs.
$('#PlatformId').empty();
$('#PartId').empty();
$('.showhide-platform').show();
// AJAX call that re-populate Platform drop down depending on the Workstation selected.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: { activityId: activityId, workstationId: workstationId },
success: function (codes) {
$('#PlatformId').append('<option value=""></option>');
$.each(codes, function (i) {
$('#PlatformId').append('<option value = "' + codes[i].Value + '">' + codes[i].Text + '</option>');
});
},
error: function (ex) {
$('#PlatformId').append('<option value=""></option>');
}
}); // END $.ajax() on GetPlatformsByWorkstationJson
}); // END $('#WorkstationId').change()

.Net RunTimeBinderException

I have a data content witch contains complex data I just need index names which seem in Dynamic View in data. In debug mode I can see the datas but cant get them..
You can see the contents of data in image below):
if(hits.Count() > 0)
{
var data = hits.FirstOrDefault().Source;
var dataaa = JsonConvert.DeserializeObject(hits.FirstOrDefault().Source);
}
I found a solution with checking if selected index has documents; if yes,
I take the first document in index, and parse it to keys(field names) in client.
here is my func:
[HttpPost]
public ActionResult getIndexFields(string index_name)
{
var node = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(
node,
defaultIndex: index_name
);
var esclient = new ElasticClient(settings);
var Documents = esclient.Search<dynamic>(s => s.Index(index_name).AllTypes().Source());
string fields = "";
if (Documents.Documents.Count() > 0)
{
fields = JsonConvert.SerializeObject(Documents.Documents.FirstOrDefault());
var data = Documents.Documents.FirstOrDefault().Source;
return Json(new
{
result = fields,
Success = true
});
}
return Json(new
{
result = "",
Success = false
});
}
and my js:
$.ajax({
url: "getIndexFields?index_name=" + $(this).val(),
type: "POST",
success: function (data) {
if (data.Success) {
var fields = JSON.parse(data.result);
var fields_arr = [];
$.each(fields, function (value, index) {
fields_arr.push(
{
id: value,
label: value
})
});
options.filters = fields_arr;
var lang = "en";//$(this).val();
var done = function () {
var rules = $b.queryBuilder('getRules');
if (!$.isEmptyObject(rules)) {
options.rules = rules;
}
options.lang_code = lang;
$b.queryBuilder('destroy');
$('#builder').queryBuilder(options);
};
debugger
if ($.fn.queryBuilder.regional[lang] === undefined) {
$.getScript('../dist/i18n/query-builder.' + lang + '.js', done);
}
else {
done();
}
}
else {
event.theme = 'ruby';
event.heading = '<i class=\'fa fa-warning\'></i> Process Failure';
event.message = 'User could not create.';
event.sticky = true;
$("#divfailed").empty();
$("#divfailed").hide();
$("#divfailed").append("<i class='fa fa-warning'></i> " + data.ErrorMessage);
$("#divfailed").show(500);
setTimeout(function () {
$("#divfailed").hide(500);
}, 3000);
}
},
error: function (a, b, c) {
debugger
event.theme = 'ruby';
event.heading = '<i class=\'fa fa-warning\'></i> Process Failure';
event.message = 'Object could not create.';
$("#divfailed").empty();
$("#divfailed").hide();
msg = c !== "" ? c : a.responseText;
$("#divfailed").append("<i class='fa fa-warning'></i> " + msg);
$("#divfailed").show(500);
setTimeout(function () {
$("#divfailed").hide(500);
}, 3000);
}
});

angularjs post data to mvc controller

I have simple code using angularjs,
$http.post(postToCreateURL, addingProducts, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function () {
})
.error(function () {
});
And I want bind this data to this Mvc controller
[HttpPost]
public JsonResult Create(ProductModel model)
{
NorthwindEntities db = new NorthwindEntities();
var products = db.Products.Select(s => new ProductModel
{
ProductName = s.ProductName,
SupplierID = s.SupplierID,
CategoryID = s.CategoryID,
QuantityPerUnit = s.QuantityPerUnit,
UnitPrice = s.UnitPrice,
UnitsInStock = s.UnitsInStock,
UnitsOnOrder = s.UnitsOnOrder,
ReorderLevel = s.ReorderLevel,
Discontinued = s.Discontinued
}).Take(5).ToList();
return Json(products, JsonRequestBehavior.AllowGet);
}
In this situation I'm getting null values. Thanks in advance!
Try this:
var request = {
ProductName: 'aa',
SupplierID: 'aa',
CategoryID: 'aa',
...
Discontinued: 'zzz'
}
$http.post(" URL IN HERE ", JSON.stringify(request), {
headers: {
'Content-Type': 'application/json'
}
})

Resources