Server Error in '/' Application on mvc jquery - javascript

he partial view Views/Shared/_RoomDetailsPartial.cshtml was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Room/Views/Shared/_RoomDetailsPartial.cshtml.aspx
hey so I'm getting this error and I have no idea why.
here is my js code in index:
function LoadRoomDetail() {
//divLoadRoomDetails
$.ajax({
async: true,
data: 'GET',
contentType: false,
processData: false,
url: '/Room/GetAllRooms',
success: function (data) {
$("#divLoadRoomDetails").html(data);
},
error: function () {
alert('There is a problem! Fix it.');
}
});
}
here is my RoomControler
public PartialViewResult GetAllRooms()
{
IEnumerable<RoomDetailsViewModel> listOfRoomDetailsViewModels =
(from objRoom in objHMSdbEntities.Rooms
join objBooking in objHMSdbEntities.BookingStatus on objRoom.BookingStatusId equals objBooking
.BookingStatusId
join objRoomType in objHMSdbEntities.RoomTypes on objRoom.RoomTypeId equals objRoomType.RoomTypeId
select new RoomDetailsViewModel()
{
RoomNumber = objRoom.RoomNumber,
RoomDescription = objRoom.RoomDescription,
RoomCapacity = objRoom.RoomCapacity,
RoomPrice = objRoom.RoomPrice,
BookingStatus = objBooking.BookingStatus,
RoomType = objRoomType.RoomTypeName,
RoomId = objRoom.RoomId
}).ToList();
return PartialView("Views/Shared/_RoomDetailsPartial.cshtml", listOfRoomDetailsViewModels);
}

Related

How to call Javascript function on Url.Action on Kendo toolbar?

I have a kendo grid with a toolbar . I added a link to download from the toolbar and now the problem is i can't call Javascript function which goes to the controller with data.
How can i call java script function on Url.Action ?
Toolbar
.ToolBar(toolBar => toolBar.Template("<a onclick='getData()' href ='" + Url.Action("", "", null, "https") + "?SeletectOrders=#= SeletectOrders#'" + ">Download Selected Orders</a>"))
If i put controller name and function, it pass an empty data to the controller and download empty file which shows at the bottom on browser. I am really not sure if am doing this correctly
Javascript function which goes to the controller
function getData(SeletectOrders)
{
$.ajax({
url: '#Url.Action("myAction", "mycontroller")',
type: "GET",
contentType: 'application/json; charset=utf-8',
dataType: "text",
data: { SeletectOrders: SeletectOrders },
traditional: true,
async: false,
cache: false,
complete: function (data) {
},
error: function () {
}
})
}
Controller
[HttpGet]
public virtual ActionResult myAction(string[] SeletectOrders)
{
List<string> ListPossDetails = new List<string>();
if (SeletectOrders != null)
{
string[] OrderArray = SeletectOrders;
foreach (var list in OrderArray)
{
ListPossDetails.Add(list);
}
}
//download methods here
Response.AppendHeader("Content-Disposition", "attachment; filename=" + possFilename);
ListPossDetails = null;
return File(fileBytes, type, possFilename);
}

Passing an array Of Objects Into An MVC .net core Controller Method Using jQuery Ajax

am using .netcore 1.1 , Visual studio 2017 , Jquery version = "3.2.1"
,am trying to make the MVC controller to get data from my page ,
i have 2 arrays in java , one is an array of Object (model view) and one is an array of strings
objects array always return error 400 (bad request)
2- string array ,always send null to the controller
i followed the below answers with no success
https://stackoverflow.com/a/13255459/6741585
and
https://stackoverflow.com/a/18808033/6741585
below is my chtml page
//#region send data back t oserver
$('#Savebtn').click(function () {
console.log(editedRows);
var UpdatedRows = JSON.stringify({ 'acActivityed': editedRows });
console.log(UpdatedRows);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/acActivity/Edit",
//traditional: true,
data: UpdatedRows ,
dataType: "json",
success: function (data) {
// here comes your response after calling the server
alert('Suceeded');
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error : " + jqXHR.responseText);
}
});
});
//#endregion
//#region deleted all selected
$('#DeleteSelectedbtn').on('click', function () {
if (confirm("Are you sure to delete All Selected ?????")) {
var selectedData = [];
var selectedIndexes;
selectedIndexes = grid.getSelectedRows();
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(grid.getDataItem(value).id);
});
console.log(selectedData);
var SelectedIds = selectedData.join(',') ;
console.log(SelectedIds);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/acActivity/DeleteSelected",
data: JSON.stringify({ "ids": SelectedIds }),
dataType: "json",
success: function (data) {
grid.render();
},
error: function (err) {
alert("error : " + err);
}
});
}
});
//#endregion
and both do have data as below console shots
the selected ID's one
my Controller
this one should expect the list of object and always return bad request ,
[HttpPost]
[ValidateAntiForgeryToken]
//public jsonResult Edit( List<acActivitytbl> acActivityed)
public ActionResult Edit( List<acActivitytbl> acActivityed)
{
foreach (acActivitytbl it in acActivityed)
{
logger.Log(LogLevel.Info, it.ID);
logger.Log(LogLevel.Info, it.Name);
logger.Log(LogLevel.Info, it.IsActive);
}
//return View(acActivityed);
return Json(new { success = true, responseText = "end of Page" });
}
that one should expect the delimited string ,but always receive null
public ActionResult DeleteSelected(string ids)
{
try
{
char[] delimiterChars = { ' ', ',', '.', ':', ' ' };
string[] words = ids.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
if (words != null && words.Length > 0)
{
foreach (var id in words)
{
bool done = true; //new acActivitiesVM().Delete(Convert.ToInt32(id));
logger.Log(LogLevel.Info, " acActivities ID {0} is Deleted Scussefully ", id);
}
return Json(new { success = true, responseText = "Deleted Scussefully" });
}
return Json(new { success = false, responseText = "Nothing Selected" });
}
catch (Exception dex)
{
..... removed to save space
});
}
}
i know there is something missing here ,but i cannot find it ,any help in that ??

Passing an array of Javascript classes to a MVC controller?

I am trying to pass an array of services to my controller.
I've tried a bunch of different ways to get it work, serializing the data before going to controller, serializing each service, only thing that seems to work is changing the controller parameter to string and serializing array, then using JsonConvert, but I'd rather not do that.
With the specified code, I am getting the correct number of items in the List, but they all contain a service id with an empty guild, and service provider id is null.
Any ideas?
Javascript
function ServiceItem() {
this.ServiceProviderID = 'all';
this.ServiceID = '';
}
var selecteditems= (function () {
var services = new Array();
return {
all: function() {
return services;
},
add: function(service) {
services.push(service);
}
};
})();
var reserved = [];
$.each(selecteditems.all(), function(index, item){
reserved.push({ ServiceID: item.ServiceID, ServiceProviderID: item.ServiceProviderID});
});
getData('Controller/GetMethod', { items: reserved }, function(result) {
});
var getData = function (actionurl, da, done) {
$.ajax({
type: "GET",
url: actionurl,
data: da,
dataType: "json",
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});
};
Controller
public JsonResult GetMethod(List<CustomObject> items)
{
}
Custom Object
public class CustomObject
{
public Guid ServiceID {get;set;}
public Guid? ServiceProviderID {get;set;}
}
Set the content-type and use POST instead of GET (as it is a list of complex type objects). mark your action with HttpPost attribute too.
See if this works:-
$.ajax({
type: "POST",
url: actionurl,
data: JSON.stringify(da),
dataType: "json",
contentType: 'application/json',
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});

Return JSON data from WebMethod and sammy.js

I'm trying to follow a Single Page App example here
Right where JSON is supposed to be parsed I get the error:
SyntaxError: JSON.parse: unexpected character if I leave out dataType: 'json'
If I put in dataTyp: 'json', then no errors, but json is not returned and my template is not filled in.
I put in a gridview just see if my list was returning...and it does.
I have loaded, jquery,sammy.js, json2.js and sammy.template.js..all latest and greatest.
I know it's example app on a diff site and I appreciate your guys' time. I just like to follow and understand as SPA apps are exciting.
javascript:
$(document).ready(function () {
//alert('Jquery has loaded');
var loadOptions = { type: 'get', dataType: 'json', cache: false };
var app = $.sammy('#sammyDiv', function () {
this.use('Template');
this.use('Session');
this.around(function (callback) {
var context = this;
this.load('Default.aspx/GetEmployees', { cache: false }) // loadOptions ) // { dataType: 'json', cache: false })
.then(function (items) {
context.items = JSON.parse(items).d; // browser parser... I believe it fails right here
//context.items = $.parseJSON(items).d; //jQuery handling
//alert(context.items);
//context.items = JSON.stringify(items);
})
.then(callback);
});
cs code:
static List<Employees> emps;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
emps = new List<Employees>();
Employees emp = new Employees("Kedar", "Kulkarni", "0001", "A");
Employees emp1 = new Employees("ABC", "XYZ", "21211", "B");
emps.Add(emp);
emps.Add(emp1);
}
/* using foreach method
foreach (Person person in persons)
{
Response.Write(String.Format("Name : {0} Age : {1} Address : {2} Job : {3}", person.Name, person.Age, person.Address, person.Job));
Response.Write("</br>");
}
*/
this.GridView1.DataSource = emps; //for testing to see if my list gets returned
this.GridView1.DataBind();
}
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static List<Employees> GetEmployees()
{
return emps;
}
finally found my answer:
I took out dataType: 'json' and replaced with below. All is good.
var loadOptions = { type: 'get', cache: false, contentType: "application/json; charset=utf-8" };

MVC JsonResult not working with chrome?

i want jquery to take a JsonResult from my MVC controller but it does'nt receive any data!
If I put the output into a textfile and enter its link its working so I think my jQuery is fine.
Then I was testing with other browsers like chrome and I saw NOTHING. The requested page was just emtpy.. no errors. Also IE seems to have problems receiving my string.. only firefox displays the string but why?
public JsonResult jsonLastRequests()
{
List<Request> requests = new List<Request>();
while (r.Read())
{
requests.Add(new Models.Request()
{
ID = (int)r[0],
SiteID = r[1].ToString(),
Lat = r[2].ToString(),
City = r[4].ToString(),
CreationTime = (DateTime)r[5]
});
}
r.Close();
return Json(requests);
}
I found out that also if I want to return the JSON as string its not working!
Its working with a string in all browsers now.. but jQuery is still not loading anything
var url = "http://../jsonLastRequests";
var source =
{
datatype: "json",
datafields: [
{ name: 'ID' },
{ name: 'SiteID' },
{ name: 'Lat' },
{ name: 'CreationTime' },
{ name: 'City' },
],
id: 'id',
url: url
};
var dataAdapter = new $.jqx.dataAdapter(source, {
downloadComplete: function (data, status, xhr) { },
loadComplete: function (data) { },
loadError: function (xhr, status, error) { }
});
I fixed my problem by adding:
access-control-allow-origin:*
public HtmlString jsonLastRequests()
{
List<Request> requests = new List<Request>();
while (r.Read())
{
requests.Add(new Models.Request()
{
ID = (int)r[0],
SiteID = r[1].ToString(),
Lat = r[2].ToString(),
City = r[4].ToString(),
CreationTime = (DateTime)r[5]
});
} r.Close();
System.Web.Script.Serialization.JavaScriptSerializer jSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return new HtmlString(jSerializer.Serialize(requests ));}
I have done same approch like this
$.ajax({
type: 'POST',
url: '/home/GetSurvey',
data: {
XmlPath: $("#xmlpath").val()
},
dataType: 'json',
success: function (jsonData) {
jsonStringQuestionaire = jsonData;
LoadSurvey();
},
error: function () {
alert('Error loading ' + id);
}
});
questionaireJsonList = eval(jsonStringQuestionaire);

Categories

Resources