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
});
});
Related
I'm building a HTML page on button click, it will transfer data from localStorage at HTML page to MVC site's action and process action then save data at MVC site
this is my HTML button 's function:
function OH10() {
var url1 = "#Url.Action('createFuel','FuelExtras')";
debugger;
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
var val = localStorage.getItem(key);
$.ajax({
type: "POST",
url: url1,
data: val,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
alert("Data has been added successfully.");
},
error: function () {
alert("Error while inserting data");
}
});
}
};
And MVC site 's action:
[HttpPost]
[System.Web.Services.WebMethod]
public ActionResult createFuel(FuelExtra fuelExtra)
{
db.FuelExtras.Add(fuelExtra);
db.SaveChanges();
string message = "SUCCESS";
return Json(new { Message = message, JsonRequestBehavior.AllowGet });
}
Any Suggestions guys?
And 1 more question is right now in development, I've build 2 sites in same Solution, but when I deploy it to intranet i have to separate it into 2 sites. Is it ok?
I found several mistakes in your example:
1) System.Web.Services.WebMethod only used in webforms, it cannot be used for ActionResult in MVC and should be removed.
2) The AJAX callback placed inside a loop, therefore it will execute multiple times instead of single request.
3) The passed data is the last localStorage value taken from getItem() function as single string, not a key-value pair reflecting model property names and their values.
Hence, by assuming you have this model:
public class FuelExtra
{
public string CaptainEmpNo { get; set; }
public string AirCraft { get; set; }
public string FlightNo { get; set; }
public string DepartureAirport { get; set; }
public string ArrivalAirport { get; set; }
// other properties
}
Then you should send key-value pair object as JSON string because the contentType setting has been set to application/json by JSON.stringify(), as in example below:
function OH10() {
var key = []; // array of keys
var val = []; // array of values
var obj = {}; // combined KVP object
var url1 = "#Url.Action("CreateFuel", "FuelExtras")";
debugger;
for (var i = 0; i < localStorage.length; i++) {
key.push(localStorage.key(i));
val.push(localStorage.getItem(key));
}
for (var n = 0; n < key.length; n++) {
obj[key[n]] = val[n]; // create KVP object from both arrays
}
$.ajax({
type: "POST",
url: url1,
data: JSON.stringify({ fuelExtra: obj }), // convert KVP object to JSON string
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("Data has been added successfully.");
},
error: function (xhr, status, err) {
alert("Error while inserting data");
}
});
};
And the controller action should be like this:
[HttpPost]
public ActionResult CreateFuel(FuelExtra fuelExtra)
{
db.FuelExtras.Add(fuelExtra);
db.SaveChanges();
return Json(new { Message = "SUCCESS" });
}
Since you're sending AJAX request as POST method, then JsonRequestBehavior.AllowGet is unnecessary.
Note:
Make sure all key names inside passed JSON string from AJAX is the same as all property names declared inside FuelExtra class.
Using ajax I want to pass 2 objects: string[] and Options to my controller. The problem is that every time string[] in controller scope is set to null.
Thats js code:
$("#exportCsv").click(function () {
var checkboxes = $('.TableChBox:checkbox:checked');
var allIds = [];
for (var i = 0, n = checkboxes.length; i < n; ++i) {
var el = checkboxes[i];
if (el.id) {
allIds.push(el.id);
}
}
console.log(allIds); // it prints ["RId1604678", "RId1604679"]
var form = $('#SearchForm').serialize();
$.ajax({
url: '#Url.Action("ExportToCsv", "Bank")',
type: 'POST',
data: JSON.stringify({
ids: allIds,
options: form
}),
dataType: 'json',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
async: true,
});
});
And thats c# code:
public void ExportToCsv(string[] ids, Options options)
{
// ids is null here
// options is not null
}
When I use debugger I can see, that options is successfully filled, but ids is null. Why does that happen?
Edit 1
As someone suggested I should Add contentType. So I added:
url: '#Url.Action("ExportToCsv", "Bank")',
type: 'POST',
contentType: "application/json; charset=utf-8",
And still - ids is not null, but options is.
Edit 2
Someone suggested to change two parameters in function to one. So I changed my code to:
part of controller
public class ExportModel
{
[JsonProperty(PropertyName = "one")]
public string One { get; set; }
[JsonProperty(PropertyName = "two")]
public string Two { get; set; }
}
[System.Web.Mvc.HttpPost]
public void ExportToCsv([System.Web.Http.FromBody] ExportModel model)
{
//model.One is null
//model.Two is null
}
part of js code
data: JSON.stringify({
one: "foo",
two: "bar"
}),
And even with that simple example with two strings it is not working.
In your controller method you should declare it as accepting a model like so:
public void ExportToCsv(ExportModel model)
{
}
And then define your model like so:
public class ExportModel
{
[JsonProperty(PropertyName = "ids")]
public string[] Ids {get;set;}
[JsonProperty(PropertyName = "options")]
public Options Options {get;set;}
}
As patilprashant6792 pointed out, your ajax request is missing the content type, so you should replace it with this:
$("#exportCsv").click(function () {
var checkboxes = $('.TableChBox:checkbox:checked');
var allIds = [];
for (var i = 0, n = checkboxes.length; i < n; ++i) {
var el = checkboxes[i];
if (el.id) {
allIds.push(el.id);
}
}
console.log(allIds); // it prints ["RId1604678", "RId1604679"]
var form = $('#SearchForm').serialize();
$.ajax({
url: '#Url.Action("ExportToCsv", "Bank")',
type: 'POST',
data: JSON.stringify({
ids: allIds,
options: form
}),
contentType: 'application/json',
dataType: 'json',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
async: true,
});
});
If you don't declare the content type, it will default to application/x-www-form-urlencoded; charset=UTF-8
You should use list of string instead of array & try.
public List<string> Ids {get;set;}
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
i have this return come from here
public string Get(int id)
{
return "{\"longPachage\":{\"Id\":0}}";
}
and i Receive this return by ajax with this code
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:3148/api/values/5",
success: function (data) {
alert(data);
alert(" Success ");
},
error: function (data) {
alert(" Error ");
}
})
what i can to deserialize json object and print the Id value only ?
You can use this code. It may be help to you.
You are not parse the data to get JSON in string format. So you can now use this code to get JSON data in string format.
var obj = JSON.parse(data);
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:3148/api/values/5",
success: function (data) {
var obj = JSON.parse(data);
alert(obj.Id);
alert(" Success ");
},
error: function (data) {
alert(" Error ");
}
})
yes, Stephen is right.
you have to send a json result from controller.
for exa.
public JsonResult Get(int id)
{
return Json(new
{
longPachage = new { ID = 0 }
}, JsonRequestBehavior.AllowGet);
}
and in your ajax success, just retrieve that object or dataID.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:3148/api/values/5",
success: function (data) {
var dataID = data.longPachage.Id;
// Do with Your ID.
},
error: function (data) {
//Do anything for error here.
}
})
Change your method like this:
public ActionResult Get(int? id)
{
return Content("{\"longPachage\":{\"Id\":0}}");
}
And then in your jQuery:
$.getJSON("http://localhost:3148/api/values", {id:5}, function(data) {
var id = data.longPachage.Id;
alert(id)
});
Try to use JsonResult in MVC to return Json instead of building a string. JsonResult is just an abstact class of ActionResult. Modify your code in the controller as follows
Method 1:
public JsonResult GetTest(int id)
{
return this.Json(new { ID = 0 }, JsonRequestBehavior.AllowGet);
}
OR
Method 2:
Try to create a model class as LongPachage
public class LongPachage()
{
public int ID {get;set;}
}
and try to invoke into the controller method as follows
public JsonResult Get(int id)
{
LongPachage model = new LongPachage();
model.ID = 0;
return this.Json(model, JsonRequestBehavior.AllowGet);
}
OR
Method 3
Create Model class say TestModel and try to add LongPachage class as propery of this class.
public class TestModel()
{
public LongPachage LongPachage {get;set;}
}
and try to invoke into the controller method as follows
public JsonResult Get(int id)
{
TestModel model = new TestModel();
model.LongPachage .ID = 0;
return this.Json(model, JsonRequestBehavior.AllowGet);
}
and then in the view using AJAX GET wrapper try to implement as follows
$.get('#Url.Action("Get","ControllerName")', { id: "5" })
.done(function (data) {
// If you are using Method 1 or Method 2 alert will be as follows
alert(data.ID);
// If you are using method 3
alert(data.LongPachage.ID)
});
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.