pass query results to ajax callback - c#

I am making a live search, where a user types something inside a text box and then via ajax results are fetched and added to a ul and in this specific case I am looking for usernames, so if a username is johnny and the user types in jo then johnny should come up and so on.
I have the ajax js code, a post method and a list model view of users, I am now trying to return the list but doesn't seem to be working.
my js:
$("input#searchtext").keyup(function (e) {
var searchVal = $("input#searchtext").val();
var url = "/profile/LiveSearch";
$.post(url, { searchVal: searchVal }, function (data) {
console.log(data);
});
});
LiveSearch view model
public class LiveSearchUserVM
{
public LiveSearchUserVM()
{
}
public LiveSearchUserVM(UserDTO row)
{
FirstName = row.FirstName;
LastName = row.LastName;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}
the post method
[HttpPost]
public List<string[]> LiveSearch(string searchVal)
{
// Init db
Db db = new Db();
List<LiveSearchUserVM> usernames = db.Users.Where(x => x.Username.Contains(searchVal)).Select(x => new LiveSearchUserVM(x)).ToList();
return usernames;
}
So basically I want to return a list (or something else) of columns that contain a specific string, and pass all the results to javascript thru ajax callback.

To return the result as JSON alter your method to the following:
[HttpPost]
public JsonResult LiveSearch(string searchVal)
{
// Init db
Db db = new Db();
List<LiveSearchUserVM> usernames = db.Users.Where(x => x.Username.Contains(searchVal)).Select(x => new LiveSearchUserVM(x)).ToList();
return Json(usernames);
}

you can use like this . The idea is to use success funtion
$.ajax({
url : ""/profile/LiveSearch"",
type: "POST",
data : searchVal ,
success: function(data)
{
//data - response from server
},
error: function ()
{
}
});
and return JsonResult from Post method

Related

Dropdown not binding data fetch from two tables

I have a dropdown list, and that list fetch it from database.But it's not binding to the dropdownlist.
In here the condition is 1 book have many BookTypes.
Here i have paste the codings.
public List<BookModel> GetBooks(string bookId)
{
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database db = factory.Create("DefaultConString");
con.Open();
String query = #"Select B.BookName,B.Author,BT.BookType
FROM VW_Book B
INNER JOIN VW_BookType BT
ON B.BookId = BT.BookId
WHERE BookId =: BookId";
cmd = db.GetSqlStringCommand(query);
db.AddInParameter(cmd, "BookId", DbType.String,bookId);
var ds = db.ExecuteDataSet(cmd);
var da = ds.Tables[0].AsEnumerable().Select(d => new StaffModel {
bookname= d.Field<string>("BookName"), //From Book table
authorname = d.Field<string>("AuthorName"), //From Book table
booktype = d.Field<string>("BookType"); // From BookType table
});
var lst = da.ToList();
return lst;
}
My Controller
[HttpPost]
public string GetBookDetails(string bookId)
{
BookBusiness bk = new BookBusiness();
List<BookModel> _book = bk.GetBookDetails("50000").ToList();
return JsonConvert.SerializeObject(_book); //
}
My Model
Public class BookModel
{
public string BookId {get;set;}
public string BookName {get;set;}
public string BookType {get;set;}
}
Ajax Call
$.ajax({
url: '#Url.Action("GetBookDetails", "Books")',
type: "POST",
async: false,
data: JSON.stringify({ BookId: BookId}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (_book) {
debugger;
$('#bookdropdown').empty();
$.each(_book, function () {
$("#bookdropdown").append(
$('<option/>', {
value: this,
html: this
})
);
});
}
});
But the issue here i face is that Data not bind to the dropdownlist.
data comes like [{"HarryPotter"}] like json format.
You ajax method expects json, so you need to change the controller method to
[HttpPost]
public JsonResult GetBookDetails(string bookId)
{
BookBusiness bk = new BookBusiness();
List<BookModel> _book = bk.GetBookDetails("50000").ToList();
return Json(_book);
}
However its unclear which of the properties of BookModel you want in the view. Only 2 properties need to be returned, one for assigning to the options value attribute, and one for the options display text (and if they are the same, then only one property needs to be returned). There is no point sending additional data across the wire which is never used so assuming you want the BookId and BookName properties, the the controller method would be
[HttpPost]
public JsonResult GetBookDetails(string bookId)
{
BookBusiness bk = new BookBusiness();
var books = bk.GetBookDetails("50000").Select(b => new
{
value = b.BookId,
text = b.BookName
};
return Json(books);
}
Then your script will be
var dropdown = $("#bookdropdown"); // cache it
$.ajax({
url: '#Url.Action("GetBookDetails", "Books")',
type: "POST",
data: { BookId: BookId }, // no need to stringify and add contnetType
dataType: "json",
success: function (books) {
debugger;
dropdown.empty();
$.each(books, function(index, item) {
dropdown.append($('<option><option/>').val(item.value).text(item.text));
});
}
});
Side note. The code you have shown will not compile. Your GetBooks() method returns List<BookModel> but its code is creating List<StaffModel>. In addition the controller is calling a method named GetBookDetails(), not GetBooks() so I assume you have shown the wrong code. In addition you pass a parameter bookId to the controller but never use it.
Try this.
$.each( _book, function( i, val ) {
$("#bookdropdown").append(
$('<option/>', {
value: val ,
text: val
});
});

500 Internal Server Error JsonResult mvc asp.net

trying to create a cascading dropdownmenu with jsonresult and ajax, but i cant see why am i getting 500 Internal Server Error. The error occurs above the following method :
[HttpGet]
public JsonResult GetModels(string brandID="")
{
List<Model> models = new List<Model>();
int ID = 0;
if (int.TryParse(brandID, out ID))
{
using (CarsEntities1 dc = new CarsEntities1())
{
models = dc.Models.Where(a => a.Brand_ID == ID).OrderBy(a =>a.Model_name).ToList();
}
}
if (Request.IsAjaxRequest())
{
return new JsonResult
{
Data = models,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
return new JsonResult
{
Data = "Not valid request",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
I use the method to pass a list of items into DropDownMenu and try to output the list by the following code :
$(document).ready(function () {
//if (typeof ($) == 'function') alert('jQuery is loaded.');
$("#brand_Brand_ID").change(function () {
// this will call when Brand Dropdown select change
var brandID = parseInt($("#brand_Brand_ID").val());
if (!isNaN(brandID)) {
var ddModel = $("#Model_ID");
ddModel.empty(); // this line is for clear all items from Model dropdown
ddModel.append($("<option></option").val("").html("Select model"));
// Here I will call Controller Action via Jquery to load Model for selected Brand
$.ajax({
url: "#Url.Action("GetModels","ModelSpec")",
type: "GET",
data: { brandID: brandID },
dataType: "json",
success: function (data) {
if (data != null && data.success) {
$.each(data, function (i, val) {
ddModel.append(
$("<option></option>").val(val.Model_ID).html(val.Model_name)
);
});
}
},
error: function () {
alert("Fail");
}
});
}
});
});
All i get is the following :
GET http://localhost:2508/ModelSpec/GetModels?brandID=2 500 Internal Server Error jquery-1.7.1.js (line 8102)
Also i noticed the error doesnt occur when theres no data passing through the GetModels method. And sometimes i get :
GET /ModelSpec/GetModels?brandID=5 401 Unauthorized
As soon as GetModels returns anything the error occurs else not.
The ObjectContext instance has been disposed and can no longer be used for
operations that require a connection
Stacktrace :
http://pastebin.com/3aXg7YiM
You need to move your return statements inside the using block
The Db context is disposed before you return statement is executed
public JsonResult GetModels(int brandID)
{
List<Model> models = new List<Model>();
using (CarsEntities1 dc = new CarsEntities1())
{
models = dc.Models.Where(a => a.Brand_ID == brandID).OrderBy(a =>a.Model_name);
if (Request.IsAjaxRequest())
{
return new JsonResult
{
Data = models.ToList(),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
return new JsonResult
{
Data = "Not valid request",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
json return type has to be primitive, so i changed the code accordingly(swap List to String[] and OrderBy to Select:
public JsonResult GetModels(int brandID)
{
String[] models;
using (CarsEntities1 dc = new CarsEntities1())
{
models = dc.Models.Where(a => a.Brand_ID == brandID).Select(a=> a.Model_name).toArray();
if (Request.IsAjaxRequest())
{
return new JsonResult
{
Data = models,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
return new JsonResult
{
Data = "Not valid request",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}

Ajax call to partial view dont bind MVC3

I choose from dropdown menu an item and click add => ajax call a method which return JsonResult this is all ok. Then this data should be send to another function PartialViewResult on server side: public PartialViewResult _SkupinaRow(skupinaRow skupinaRow), which generate a new tr with some textbox and labels. My problem is that no binding is made. I get Null when debuggin in _SkupinaRow(skupinaRow skupinaRow)
I have the following domain model defined:
public class skupinaRow
{
public BONUSMALUS bonusmalus { get; set; } //items
public KOLEDAR koledar { get; set; } //calendar
}
Partial View:
#model ObracunPlac.ViewModel.skupinaRow
#Html.HiddenFor(x => x.bonusmalus.bon_id)
.....
Partial view code:
public PartialViewResult _SkupinaRow(skupinaRow skupinaRow)
{
return PartialView("_SkupinaRow", skupinaRow);
}
Ajax Call:
$("#addItemPrihodki").live("click", function () {
var id = $("#prihodkidodaj option:selected").val()
var skupinaRow = {
bonusmalus:{},
koledar:{}
}
jQuery.getJSON("/Placa/getBonusMalus/?id=" + id, function (data) {
console.log("JSON Data: " + data.koledar.kol_id);
skupinaRow.koledar.kol_id = data.koledar.kol_id, //ok
skupinaRow.bonusmalus.bon_id = data.bonusmalus.bon_id, //ok
//alert(JSON.stringify(GetBonusMalusModel($("#bonusdodaj option:selected").val())));
alert(JSON.stringify(data));
// alert(skupinaRow.serialize());
$.ajax({
url: "../_skupinaRow",
cache: false,
data: JSON.stringify(skupinaRow),
//data: JSON.stringify(data),
datatype: JSON,
success: function (html) {
$("#editorRowPrihodki table tr#dodajNov").before(html);
}
,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error'+"+++"+textStatus+"--- "+errorThrown);
},
});
});
return false;
});
public JsonResult getBonusMalus(int id)
{
KOLEDAR koledar = db.KOLEDAR.Single(r => r.kol_id == KoledarID);
BONUSMALUS bm = db.BONUSMALUS.Single(r => r.bon_id == id);
skupinaRow model = new skupinaRow
{
koledar =koledar,
bonusmalus = bm
};
// return Json result using LINQ to SQL
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = model
};
}
Debug picture: https://www.dropbox.com/s/189q080irp0ny77/1.jpg
This worked when i had one model bonusmalus but now I ned two so I created modelView.
How can I bind ViewModel-SkupinaRow to Partial View with strong type SkupinaRow ?
If you are using AJAX only to convert he value to json? then you can use this approach
Set the form with normal post back to Action in controller
use jQuery in your view and on submit of form write this.
$("form").submit(function(){
$("#DropDown_Items").val(JSON.stringify(data));
});
Now you can use this in your Action Method.

How do I access parameters of my POST request within a controller

Javascript:
$.post("/DataAPI/messageProcessor", { query: "Hello World!" }, function (data) {
Handle(data);
}
});
Controller:
[System.Web.Http.AcceptVerbs("Post")]
[System.Web.Http.ActionName("messageProcessor")]
public ResponseModel messageProcessor(string query)
{
ResponseModel model=DoStuff(query);
return model;
}
How do I access query from the controller. It always arrives as query == null. There is Request object available too but I am not sure how to navigate through its members to reach my "Hellow World!".
You need to pass name-value pairs from the client:
$.post("/DataAPI/messageProcessor"
, { query: "Hello World!" }
, function (data) {} );
Check jQuery.Post for more details.
try this :
$.post("/DataAPI/messageProcessor", { 'query' : 'Hello World!' }, function (data) {
Handle(data);
}
});
Thanks to a coworker. Solution is as following:
public class QueryClass
{
public string query { get; set; }
}
public ResponseModel messageProcessor(QueryClass query)
{
ResponseModel model=DoStuff(query.query);
return model;
}

What is the use case for using a JsonResult action in asp.net mvc3?

When is it typical to use the JsonResult action in an ASP.NET MVC 3 application?
From where is the JsonResult usually called; from another action or an actionlink rendered in the html?
Can you give me some examples where you want json instead of a typical view?
Say, for example you wanted to populate a jQuery autocomplete with a list of values based on a selection of another field, so you can't determine the data on page load. I would typically call an action method in a $.ajax call, then return an array of items to populate the autocomplete with.
Example, here's my jQuery, one function for the call and another that gets called to populate the automcomplete with received data:
$(function() {
$.ajax({
url: '#Url.Action("GetHomes", "Account")',
type: "POST",
datatype: "json",
success: function (data) {
if (data.Success || data.Success == null) {
WireUpHomesData(data);
} else {
ShowErrorDialog();
}
}
});
ShowDialog();
});
function WireUpHomesData(data) {
var homes = new Array();
for (var i = 0; i < data.length; i++) {
homes[i] = { label: data[i].HomeName, text: data[i].HomeId, icon: data[i].HomeIcon, desc:data[i].HomeAddress };
}
$("#home").autocomplete({
source: homes,
select: function (event, item) {
homeUrl = '#Url.Action("Site", "Sites")/' + item.item.text;
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a><span class='" + item.icon + "'/><span class='fs-ui-autocomplete-home'>" + item.value + "</span><br>" + item.desc+ "</a>")
.appendTo(ul);
};
$(".ui-autocomplete").addClass("fs-ui-autocomplete");
}
And here is my controller:
public JsonResult GetHomes()
{
return Json(RequiresAclAttribute.HomesForUser());
}
And here's the method signature for the method that's called:
public IEnumerable<HomeInfo> HomesForUser()
And for clarity, here's the HomeInfo class:
public class HomeInfo
{
public string HomeId { get; set; }
public string HomeName { get; set; }
public string DisplayName { get; set; }
public string HomeAddress { get; set; }
public string HomeIcon { get; set; }
}
JsonResult is a subclass derived from ActionResult class. You can use this when you want to return a Json object.
public JsonResult GetItems()
{
var jsonResult=new { Id = "23", Name = "Scott"};
return Json(jsonResult,JsonBehaviour.AllowGet);
}
This will return the same result as
public ActionResult GetItems()
{
var jsonResult=new { Id = "23", Name = "Scott"};
return Json(jsonResult,JsonBehaviour.AllowGet);
}
Possible use of this is to get some chunk of data in asynchronous way. Ex : Imagine you have a drop down where you are showing the states and when user selects a state, you want to to bring the list of cities belongs to the state and show it in the page without a page refrest. you can call use jQuery ajax /getJson method (short hand of jQuery get with json as datatype) method to get this data from an ActionMethod which returns Json data.
A small example to call an Action method which returns the Json data
$(function(){
$.getJSON('YourController/GetItems', function(data) {
alert(data.Id);
alert(data.Name );
});
});
With JsonResult class the response content type will be "application/json" if nothing is specified explicitly. Internally The ExecuteResult method uses JavaScriptSerializer to Serialize the content when returning data.
The JsonResult is very usefull wehn making ajax calls from javascript, e.g. using getJSON from jQuery: http://api.jquery.com/jQuery.getJSON/
The benefit of JsonResult is it returns a JSON formatted result without effort.
An Ajax request from a client script that does not involve a full page load. Basically.
Whenever there is client side processing and client need that data use jsonresult like in autofill or remote validation

Categories

Resources