Can I serialize data to send to a Infragistics isgrid using json instead of sending a IQueryable<T> object? - asp.net-mvc

I'm using an Infragistics isGrid defined below. Is there anyway I can get it to work with a json string instead of an IQueryable object?
function bindSitesGrid() {
try {
$("#TheftGrid").igGrid({
}
]
});
var parameters = $('#VTRModifiedCriteriaForm').serialize();
var url = '/VTR/VehicleTheftRecovery/Search/?ticks=' + new Date() + "&" + parameters;
$('#TheftGrid').igGrid('option', 'dataSource', url);
}
catch (error) {
console.log(error)
}
}
So can I do this
Public Function Search(ssViewModel As VehicleTheftRecoveryVM) As ActionResult
Return View(Json(siteSearchResults))
End Function
Instead of this
Public Function Search(ssViewModel As VehicleTheftRecoveryVM) As ActionResult
Return View(siteSearchResults.AsQueryable())
End Function

Related

Showing error message after checking the back-end

My controller is something like this:
[HttpPost]
[Route("Somewhere")]
public JsonResult SetSomething(string propertyName, string propertyValue)
{
var successSave = this.SaveIt(propertyName,propertyValue);
if(successSave)
return Json(propertyValue);
else
// Show a message in front end that there was problem in saving
}
And then my view is currently something like:
#Model.SomethingFeild
That just loads the value and shows it in a textbox field in there .
So how can I change this to be able to handle the psedo-code scenario I wrote in the controller, so that if something is wrong in DB ( not front-end vlaidation) such as duplicate entry, then it comes back and tells the UI that so UI shows a hard coded message?
Wrap it in try catch block and add an extension method for reading exception (or your exception type that is thrown) like so:
[HttpPost]
[Route("Somewhere")]
public JsonResult SetSomething(string propertyName, string propertyValue)
{
try
{
var successSave = this.SaveIt(propertyName, propertyValue);
if (successSave)
return Json(new { success = true, value = propertyValue });
}
catch (Exception ex)
{
return Extensions.ReturnExceptionToView(ex);
}
}
Example extension method (static method):
internal static JsonResult ReturnExceptionToView(Exception ex)
{
List<object> viewErrors = new List<object>();
viewErrors.Add(new { ErrorMessage = ex.ToString() });
return new JsonResult() { Data = (new { success = false, errors = viewErrors }) };
}
Then check for success property in the response in JS. Example below is using response of ajax call and pushing to Knockout observable array.
if (response.success) {
// do something with successful response
} else {
// we have an error in the response.errors collection
$.each(response.errors, function () {
vm.saveErrors.push(new ErrorMsg(this.ErrorMessage));
});

ASP.Net MVC, WebAPI, AngularJS - Check if value exists in database

I am using webapi and angularjs in my ASP.net MVC app. Everything is working good but in my insert (post) method I need to check if a value exists in the db before doing an insert. I am not sure where that should go. I ruled out the webapi because a void does not return a value. The logical place seems to be the controller, but I cannot find the right way to call my angular getEmployee(id) method from within the insert controller method. Any help is appreciated.
Angular controller (post):
$scope.insertEmployee = function (employee) {
employeeFactory.insertEmployee(employee)
.success(function (emp) {
$scope.employee = emp;
})
.error(function (error) {
$scope.status = 'Unable to load employee data: ' + error.message;
});
};
Angular factory (post):
factory.insertEmployee = function (employee) {
url = baseAddress + "employee/insert/";
$http.post(url, employee).success(function (data) {
alert("Saved Successfully!!");
}).error(function (data) {
$scope.error = "An Error has occured while saving employee! " + data;
});
};
webapi controller post method:
[Route("api/employee/insert/")]
public void Post(Employee employee)
{
if (ModelState.IsValid)
{
context.Employee.Add(employee);
context.SaveChanges();
}
}
Angular controller (get):
$scope.getEmployees = function (term) {
employeeFactory.getEmployees(term)
.success(function (data) {
$scope.employees = data;
})
.error(function (error) {
$scope.status = 'Unable to load employee data: ' + error.message;
});
};
I would suggest doing this in your web-api server side. You can construct an exception and throw it. Some pseudo-code:
[Route("api/employee/insert/")]
public void Post(Employee employee)
{
if (ModelState.IsValid)
{
// verify doesn't already exist
if(...item-already-exists...) {
var resp = new HttpResponseMessage(HttpStatusCode.Conflict)
{
Content = new StringContent("Employee already exists!")),
ReasonPhrase = "Employee already exists!"
}
throw new HttpResponseException(resp);
}
context.Employee.Add(employee);
context.SaveChanges();
}
}
Your factory doesn't match your controller. If you want to use success and error from employeeFactory.insertEmployee, it needs to return the promise:
factory.insertEmployee = function (employee) {
url = baseAddress + "employee/insert/";
return $http.post(url, employee);
};
So then you can do
employeeFactory.insertEmployee(employee).success( ... )
Now to answer your question you could either do a database read in insertEmployee to check if the value exists before you insert it. Or save a server call and do the check during the insert request: if the employee exists, return an error or a specific message to tell the client.
With the help of floribon and Nicholas Smith I managed to come up with a solution that bubbles the error up to my view, which I display in a div element. This is only bare bones, but is a start.
My angular controller:
$scope.insertEmployee = function (employee) {
employeeFactory.insertEmployee(employee)
.success(function (data) {
$scope.employee = data;
$scope.status = 'The item was saved';
})
.error(function (error) {
$scope.status = 'Unable to save the employee data: ' + error;
});
};
My angular factory:
factory.insertEmployee = function (employee) {
url = baseAddress + "employee/insert/";
return $http.post(url, employee);
};
my webapi controller:
[Route("api/employee/insert/")]
public HttpResponseMessage Post(Employee employee)
{
HttpResponseMessage response;
// check for the employee
var employeeCheck = context.Employee
.Where(b => b.EmployeeNumber == employee.EmployeeNumber)
.FirstOrDefault();
if (employeeCheck == null)
{
// save the item here
response = Request.CreateResponse(HttpStatusCode.OK);
}
else
{
response = Request.CreateResponse(HttpStatusCode.Conflict, "The item already exists");
}
return response;
}
The result is the message is "Unable to save the employee data: The item already exists".

ASP.NET MVC Web API : Posting a list of objects

I'm trying to post a list of objects from my winforms application to my asp.net mvc 4 website. I've tested posting one object, and it works, but does not work for the list. It returns a 500 (Internal Server Error). Here is my code:
ASP.NET MVC Web API
public class PostTraceController : ApiController
{
public HttpResponseMessage Post(List<WebTrace> list)
{
try
{
// Some code
return Request.CreateResponse(HttpStatusCode.Created);
}
catch (Exception ex)
{
HttpContext.Current.Trace.Write("exception", ex.Message);
return Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, ex);
}
}
public HttpResponseMessage Post(WebTrace item)
{
try
{
// Some code
return Request.CreateResponse(HttpStatusCode.Created);
}
catch (Exception ex)
{
HttpContext.Current.Trace.Write("exception", ex.Message);
return Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, ex);
}
}
}
Win forms application
public class BaseSender
{
public BaseSender()
{
Client = new HttpClient
{
BaseAddress = new Uri(#"http://localhost/mywebsite/")
};
Client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public string UserCode { get; set; }
protected readonly HttpClient Client;
public HttpResponseMessage PostAsJsonAsync(string requestUri, object value)
{
var response = Client.PostAsJsonAsync(requestUri, value).Result;
response.EnsureSuccessStatusCode();
return response;
}
}
public class WebTraceSender : BaseSender
{
private const string requestUri = "api/posttrace";
public bool Post(List<ArchiveCptTrace> list)
{
try
{
var listWebTrace = new List<WebTrace>();
foreach (var item in list)
{
listWebTrace.Add(new WebTrace
{
DateStart = item.DatePreparation,
DateEnd = item.DateCloture,
UserStart = item.UserPreparation.UserName,
UserEnd = item.UserCloture.UserName,
AmountStart = item.MontantPreparation,
AmountEnd = item.MontantCloture,
TheoricAmountEnd = item.MontantTheorique,
Difference = item.Ecart,
UserCode = UserCode
});
}
var responce = PostAsJsonAsync(requestUri, listWebTrace);
return responce.IsSuccessStatusCode;
}
catch (Exception e)
{
// TODO : Trace the exception
return false;
}
}
}
EDIT :
I've found out the scenario of the error, which is having two methods in my api controller, even thought they have different signature. If I comment one method, the post work fine (item or a list). Any ideas ?
The methods may have different signatures, but Web API can't tell the difference between them without inspecting the body, which it won't do for performance reasons.
You could do two things - either create a new class which just holds a list of WebTrace objects, and put that in a different API controller, or you could map a custom route to one of your existing methods. You could do that with ActionName attribute, however, I would probably take the first approach.

Sending Data From javaScript Which Is retrived from LocalStorage(WebSql) and pass to MVC Controller

db.transaction(
function (transaction) {
transaction.executeSql('INSERT INTO EmployeeTable(Firstname,Lastname,BirthDate,EmployeeType,MaritalStatus,Company,IsActive,Dependents) values(?,?,?,?,?,?,?,?)',
[Firstname.toString(), Lastname.toString(), BirthDate, parseInt(empType), parseInt(marital),Company.toString(),active, parseInt(Dependents)]);
transaction.executeSql('SELECT * FROM EmployeeTable', [], function (transaction, results) {
result = results;
alert(result.length);
for (i = 0; i < results.length; i++) {
var EmployeeID = results.rows.item(i).EmployeeID;
var Firstname = results.rows.item(i).Firstname;
var Lastname = results.rows.item(i).Lastname;
alert(results.rows.item(i).EmployeeID + " " + results.rows.item(i).Firstname + " " + results.rows.item(i).Lastname);
//var product = [productid, productname, price, qty];
//insertTableRow(product,i);
}
}, null);
}
);
am Using WEB SQL as Local Database
want to send data retrived from websql using
db.Transaction() method
to server controller.
Please Help On same.....
How should i transfer data to controller of mvc.....
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
if (Save(0, collection))
{
// List<char> bulkdata = collection["bulkdata"].ToList();
return RedirectToAction("Index");
}
else
{
return View("Edit");
}
}
catch
{
return View();
}
}
The following tutorial shows an example how to sync local db with a WCF Data Service endpoint. By combining this with the WebAPI tutorial you will be able to sync to the online DB with these lines:
function synchronizeData() {
offlinedb
.TodoItems
.filter("it.InSync === false")
.toArray(function (todoItems) {
onlinedb.addMany(todoItems);
onlinedb.saveChanges(function () {
todoItems.forEach(function (todoItem) {
offlinedb.attach(todoItem);
todoItem.InSync = true;
});
offlinedb.saveChanges(function () {
listLocalTodoItems();
listRemoteTodoItems();
});
});
})
}
You might try serializing your localstorage string and then send to the server...
ASP.NET MVC How to pass JSON object from View to Controller as Parameter

Returning Json data from MVC controller

public ActionResult About()
{
List<Stores> listStores = new List<Stores>();
listStores = this.GetResults("param");
return Json(listStores, "Stores", JsonRequestBehavior.AllowGet);
}
Using the above code I am able to get the below result
[{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555","email":"abc#ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454","email":"nfnf#ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},
How would I able to get the result in below format?
{
"stores" : [
{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555","email":"abc#ac.com",
"geo":{"latitude":"12.9876","longitude":"122.376237"}},
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454","email":"nfnf#ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}} ]
}
I would like to have the stores at the beginning of the data.
Please help me in this regard.
You will need to create an object that contains the stores within a property named stores:
public ActionResult About()
{
var result = new { stores = this.GetResults("param") };
return Json(result, "Stores", JsonRequestBehavior.AllowGet);
}
I've used an anonymous type for simplicity here, if this result type were required in multiple places you may consider creating a 'proper' class for it.
JavaScriptSerializer can be found from namespace System.Web.Script.Serialization
var ser = new JavaScriptSerializer();
var jsonStores = ser.Serialize(stores);
return Json(new { stores: jsonStores }, "Stores", JsonRequestBehavior.AllowGet);
if you want to send object to client side as Json format
like Data-table,List,Dictionary etc. then need to override jsonResult and ExecuteResult
other wise use linq format to return data
like
using JSON.NET(must need to use override jsonResult and ExecuteResult )
DataTable dt = new DataTable();//some data in table
return json("data",JsonConvert.SerializeObject(dt))
other option using linq
var Qry = (from d in dt.AsEnumerable()
select new
{
value = d.Field<int>("appSearchID"),
text = d.Field<string>("appSaveSearchName"),
type = d.Field<int>("appSearchTypeStatus")
});
return json("Data", Qry);
override methods
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
try
{
return new JsonNetResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
MaxJsonLength = int.MaxValue
};
}
catch (Exception)
{
throw;
}
}
public class JsonNetResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
try
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (this.Data == null)
return;
using (StringWriter sw = new StringWriter())
{
response.Write(this.Data);
}
}
catch (Exception)
{
throw;
}
}
}
public class StoresViewModel{
public List<Stores> stores {get;set;}
}
public ActionResult About()
{
List<Stores> listStores = new List<Stores>();
listStores = this.GetResults("param");
StoresViewModelmodel = new StoresViewModel(){
stores = listStores;
}
return Json(model, JsonRequestBehavior.AllowGet);
}

Resources