Display list using ajax - javascript

Why after clickin on the button it display's nothing. And it do not invoke BooksByPublisherId. What i missed? How to fix this?
Controller
public class FoodController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult BooksByPublisherId(int id)
{
IList<BookModel> modelList = new List<BookModel>();
modelList.Add(new BookModel { Author = "Jhon", Year = "1970" });
modelList.Add(new BookModel { Author = "Nick", Year = "1977" });
modelList.Add(new BookModel { Author = "Joseph", Year = "1978" });
return Json(modelList, JsonRequestBehavior.AllowGet);
}
}
Model
public class BookModel
{
public string Title { get; set; }
public string Author { get; set; }
public string Year { get; set; }
public decimal Price { get; set; }
}
View
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/knockout-2.2.0.js"></script>
<h2>Index</h2>
<button data-bind="click: capitalizeLastName">Load list</button>
<div class="results">Wait for list</div>
<script>
function AppViewModel() {
this.capitalizeLastName = function () {
debugger;
$.ajax({
cache: false,
type: "GET",
url: "Food/BooksByPublisherId",
data: { "id": id },
success: function (data) {
var result = "";
$.each(data, function (id, book) {
result += '<b>Title : </b>' + book.Title + '<br />' +
'<b> Author :</b>' + book.Author + '<br />' +
'<b> Year :</b>' + book.Year + '<br />' +
'<b> Price :</b>' + book.Price + '<hr />';
});
$('.results').html(result);
},
error: function (response) {
debugger;
alert('eror');
}
});
}
}
ko.applyBindings(new AppViewModel());
</script>

The only problem i can see in your code is, you are using a variable called id to build the js object you sent as the data for the ajax call, but it is not declared and initialized any value to it. In that you will get a script error like
Uncaught ReferenceError: id is not defined
Because of this script error, your other js code won't work ! As you see, the error is self explanatory. Just declare a variable id and set some value to it.
var id = 911;
$.ajax({
type: "GET",
url: "Food/BooksByPublisherId",
data: { "id": id },
// Your existing code
});
Also i see you have hardcoded the path to your action method. A better approach is to use the Html helper methods like Url.Action method to build the correct relative path to the action method.
url: "#Url.Action("BooksByPublisherId","Food")",
This will work if your js code is inside a razor view. If your code is inside an external js file, you might use the solution explained in this post.

Related

I can't pull data from ajax

public enum SocialEnum
{
[Display(Name = "Genel")]
General,
[Display(Name ="Teşekkür Et")]
Thanks
}
public class SocialMedia : Entity<string>
{
public string Message { get; set; }
public string Departmen { get; set; }
public SocialEnum MessageType { get; set; }
public string FullName { get; set; }
}
This is my model
<div class=" right floated" id="SubjectButtons">
<button class="tiny ui inverted blue button General" id="general"><i class="globe icon"></i>Genel</button>
<button class="tiny ui inverted blue button Thanks" id="thanks"><i class="star icon"></i>Teşekkür Et</button>
</div>
this is my cshtml
$(function () {
$('#Share').on('click', function () {
var file = $("#imgupload").get(0).files;
var droplist = $(".ui.fluid.search.dropdown").val();
var message = $(".ui.form").val();
var sbjtbtn = $("#general").val();
var sbjtbtn = $("#thanks").val();
var data = new FormData;
data.append("Photo", file[0]);
data.append("Message", message);
data.append("FullNameList", droplist);
data.append("MessageType", sbjtbtn);
$.ajax({
url: '#Url.Action("Index")',
type: "POST",
data: data,
contentType: false,
processData: false,
success: function (data) {
$(".post-area").html(Counter);
$(".post-area").html(data);
$("#message").html(data.message);
$(".img-responsive").append('<img src="/Image/' + data + '"class=img-responsive thumbnail"/>');
if (sbjtbtn == $("#thanks")) {
$("#person").html(data.droplist);
$(".post-area").html(data);
$("#message").html(data.message);
$(".img-responsive").append('<img src="/Image/' + data + '"class=img-responsive thumbnail"/>');
}
},
error: function (data) {
}
});
});
});
this is my js
public ActionResult Index(SocialMedia data)
{
var model=GetSocialMedia();
MediaList mediaList = new MediaList();
if (mediaList.MessageType == data.MessageType)
{
mediaList.FullName = model.FullName;
mediaList.Departmen = model.Departmen;
mediaList.Message = data.Message;
var file = data.Photo;
if (file != null)
{
string Location = Server.MapPath("/Image/" + file.FileName);
file.SaveAs(Location);
mediaList.Photo = "../Image/" + file.FileName;
}
mediaList.FullNameList = data.FullNameList;
}
return PartialView("~/Views/SocialMedia/MediaList.cshtml", mediaList);
}
This is my controller
When you press the general button, some data should come. but if you press the thanks button, it should pull more data. I have defined it separately in ajax. I gave the variable name the same. message type comes in general.The message type is never be thanks.Where is my mistake?
My index page, model and controller are longer, but I think these are the parts I need to show.Sorry for my English:)
you should know already what is the difference between view and model. In any case in index view place this div
.....
<div id="mediaList">
<partial name="~/Views/SocialMedia/MediaList.cshtml" />
</div>
.....
<div class=" right floated" id="SubjectButtons">
<button class="tiny ui inverted blue button General" id="general"><i class="globe icon"></i>Genel</button>
<button class="tiny ui inverted blue button Thanks" id="thanks"><i class="star icon"></i>Teşekkür Et</button>
</div>
and ajax
$.ajax({
url: '#Url.Action("Index")',
.....
success: function (data) {
$("#mediaList").html(data);
},
error: function (xhr) {
}
});
have you tried using POSTMAN tool? https://www.postman.com/ . This tool is used for testing webservice API. Try this one first if you really get some data from your API URL.

Use jscript and controller actions to add data to database using MVC ASP.net

I need to save data to a database from my MVC ASP.net project without refreshing the view page. To do this I plan to create a string and send it to the controller to then send to the database. I have already made a function to create the string...
function CreateChain() {
RecordID = document.getElementById("RecordIdTextBox").value
RecordDate = document.getElementById("RecordDateEntry").value
Employee = document.getElementById("EmployeeTextBox").value
Department = document.getElementById("ddlDepartmentsOption").value
SubDepartment = document.getElementById("ddlSubDepartments").value
Machine = document.getElementById("ddlMachines").value
Equipment = document.getElementById("ddlEquipment").value
Problem = document.getElementById("InvisibleProblemsddl").value
Grade = document.getElementById("Gradeddl").value
GradeComment = document.getElementById("GradeComment").value
WorkOrderStatus = document.getElementById("WorkOrderStatus").value
WorkOrderNumber = document.getElementById("WorkOrderNumber").value
chain = ("RecordID:" + RecordID + ',' +
"RecordDate:"+ RecordDate + ',' +
"Employee:"+ Employee + ',' +
"DepartmentID:"+ Department + ',' +
"SubDepartmentID:"+ SubDepartment + ',' +
"MachineID:"+ Machine + ',' +
"EquipmentID:"+ Equipment + ',' +
"ProblemID:"+ Problem + ',' +
"Grade:"+ Grade + ',' +
"GradeComment:"+ GradeComment + ',' +
"WorkOrderStatus:"+ WorkOrderStatus + ',' +
"WorkOrderNumber:"+ WorkOrderNumber)
console.log(chain);
}
And an example of the string looks like this
RecordID:5,RecordDate:2021-08-02T13:50:46,Employee:Josh,DepartmentID:1,SubDepartmentID:1,MachineID:16,EquipmentID:141,ProblemID:59,Grade:A,GradeComment:the machine is working,WorkOrderStatus:true,WorkOrderNumber:123456
How can I 1.) Send this string to the controller and 2.) Use the controller to send this to my database?
All data points correspond to table RecordEntry in my database and have the same name as given.
EDIT:
This is my function in view now. When ran it does not get down to the alert(chain). Do you know why? The other alert that is commented out does hit.
EDIT: I realized that you did not have the ajax within the function and I did there. Should it be in the function so it is called on a submit button press?
function CreateChain() {
//alert("running function createchain");
Record = document.getElementById("RecordIdTextBox").value
RecordDate = document.getElementById("RecordDateEntry").value
Employee = document.getElementById("EmployeeTextBox").value
Department = document.getElementById("ddlDepartmentsOption").value
SubDepartment = document.getElementById("ddlSubDepartments").value
Machine = document.getElementById("ddlMachines").value
Equipment = document.getElementById("ddlEquipment").value
Problem = document.getElementById("InvisibleProblemsddl").value
Grade = document.getElementById("Gradeddl").value
GradeComment = document.getElementById("GradeComment").value
WorkOrderStatus = document.getElementById("WorkOrderStatus").value
WorkOrderNumber = document.getElementById("WorkOrderNumber").value
return {
"RecordID": Record,
"RecordDate": RecordDate,
"Employee": Employee,
"DepartmentID": Department,
"SubDepartmentID": SubDepartment,
"MachineID": Machine,
"EquipmentID": Equipment,
"ProblemID": Problem,
"Grade": Grade,
"GradeComment": GradeComment,
"WorkOrderStatus": WorkOrderStatus,
"WorkOrderNumber": WorkOrderNumber
};
var chain = CreateChain();
alert(chain);
$.ajax({
url: "/RecordEntries/AddtoDatabase",
type: "POST",
data: { model: chain },
success: function (result) {
alert("Success");
},
error: function (xhr, exception) {
alert("Error");
}
});
}
This is my submit (next) button
<a class="btn btn-success btn-block btn-lg " onclick="NextButtonClick()" id="nextbutton"><font color="white">Next</font></a>
And the function that is called that calls multiple other functions.
function NextButtonClick() {
HideSelectionsBeforeNextSelection();
ShowDropDownsAgain();
//removefromList();
ResetValues();
IncreaseRecordIdByOne();
CreateChain();
}
Try this
javasript
function CreateChain() {
//alert("running function createchain");
var Record = document.getElementById("RecordIdTextBox").value;
var RecordDate = document.getElementById("RecordDateEntry").value;
........
var chain= {
RecordID: Record,
RecordDate: RecordDate,
.....
};
alert( JSON.stringify( chain));
$.ajax({
url: "/mycontroller/myaction",
type: "POST",
data: { model: chain },
success: function (result) {
alert(result);
},
error: function (xhr, exception) {
alert("Error");
}
});
}
Server side
you have to create viewmodel
public class ChainViewModel
{
public int RecordID {get; set;}
public string RecordDate {get; set;}
public string Employee {get;set;}
....and so on
}
controller
public class MyController :Controller
{
public ActionResult MyAction( ChainViewModel model)
{
....use model data to submit to db
return Ok("Success");
}
}

public action method was not found on the controller

I'm getting an error that my Action Method was not found, but can't figure out what's wrong. I searched the internet now for hours but haven't found a solution till now.
In my View I have a JavaScript function:
<script type="text/javascript">
function ShowHideAds(button) {
var dAds = document.getElementById("dAds");
if (dAds.style.display == "none") {
dAds.style.display = "block"
var txtBox = "Visible";
$.post('#Html.Action("GetState","Rights")', { txtAds: txtBox });
}
else {
dAds.style.display = "none"
var txtBox = "Hidden";
$.post('#Html.Action("GetState", "Rights")', { txtAds: txtBox });
}
} </script>
I'm switching between a Textbox and a Listbox and depending on which is visible, I want to pass the parameter to my method.
My method in my Controller is the following:
[HttpPost, ActionName("GetState")]
public ActionResult GetState(string txtAds, string txtRg)
{
if (txtAds != null)
stateTxtAds = txtAds;
if (txtRg != null)
stateTxtRg = txtRg;
return View();
}
and finally here is my routing:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Before using the #Html.Action() method I had following line of code:
$.post("/Rights/GetState", { txtAds: txtBox });
but this did not work when the project was deployed so I tried to use the #Html.Action two send my variables to my controller method.
Can anyone help please?
Thank you!
GetState(string txtAds, string txtRg) has two parameters but you are only providing one. If you want it to accept two but only provide it one like you are doing in the call, do the following.
For example for the post #Html.Action("GetState", "Rights")', { txtAds: txtBox }:
GetState(string txtAds, string txtRg = "")
This way you can just send txtAds if you want and it should reach it.
The ajax I would recommend:
var json = '{txtAds: "' + txtAds + '"}'
$.ajax({
url:'#Url.Action("GetState", "Rights")',
type:'POST',
data: json,
contentType: 'Application/json',
success: function(result){
// Whatever you want to do next.
}
})

Trying to display 4 concate item in dropdownlist from database

I'm trying to bind and display 4 concatenate item in dropdownlist using ajax.
Like this eg. (127,CoilWt,1,KGS ) one of the value in dropdownlist should appear like this.from database.
In database i am selecting
`select CODE_VALUE,CODE_DESC,CODE_SUB_VALUE,CODE_SUB_DESC FROM TCODE
html part
<td><select class='form-control' id='Certific'><option value='' disabled='disabled' selected='selected'>Please select a name</option></select></td>
script part
$(function () {
$.ajax({
type: "POST",
url: "TDC.aspx/GetCertificate",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var Certific = $("[id*=Certific]");
Certific.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(r.d, function () {
Certific.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
});
});
c# side
public class GetCertificate
{
public int ID { get; set; }
public string Code_Desc { get; set; }
}
[WebMethod]
public static List<GetCertificate> GetCertificate()
{
string connStr = ConfigurationManager.ConnectionStrings["conndbprodnew"].ToString();
OracleConnection objconn = new OracleConnection(connStr);
string prop_name, tdc_property = "", qry = "";
qry = "SELECT CODE_DESC from tdc_product1 ";
OracleCommand objFetchCmd = new OracleCommand(qry, objconn);
List<GetCertificate> Certificate = new List<GetCertificate>();
objconn.Open();
OracleDataReader ReadData = objFetchCmd.ExecuteReader();
while (ReadData.Read())
{
GetCertificate.ID = ReadData["ID"].ToString();
GetCertificate.CODE_DESC = ReadData["CODE_DESC"].ToString();
}
return Certificate;
}
Where is the mistake i am trying like this but getting error at GetCertificate.ID .Any idea would be appreciated.
I guess you're making mistake at:
GetCertificate.ID = ReadData["ID"].ToString();
GetCertificate.CODE_DESC = ReadData["CODE_DESC"].ToString();
GetCertificate seems to be a type not a instance of object.
You should try something like:
Certificate.Add(new GetCertificate { ID = ReadData["ID"].ToString(), CODE_DESC = ReadData["CODE_DESC"].ToString() } );
Please be aware that I wrote this without any IDE, so there could be typo/syntax error, but you get the idea.
Small hint: Of course there're plenty of room for code refactor in your code (e.g. rename Certificate to Certificates), but that is another topic.

Populating second DropDownList based on the selected value of first DropDownList in MVC2

I had the same problem as shown in this question so I tried his solution, but I couldn't make it work, probably because of my tiny knowledge of jquery and javascript. When I debug it in Firebug, I saw that it breaks at line:
$.post('<%: ResolveUrl("~/Home/GetSubcategories/")%>' + $("#ddlCats > option:selected").attr("value"), function (data) {
I have a correct action, and it should accept $("#ddlCats > option:selected").attr("value") as parameter, but it never invoke that action, so it never returns JSON data, so it never populate second DDL. What am I doing wrong? Am I missing something?
Here is my model:
public class DdlModel
{
public long Id { get; set; }
public string Name { get; set; }
}
Here is controller:
public class HomeController : Controller
{
public ActionResult Index()
{
List<DdlModel> cats = DB.Category.FindCategories();
SelectList ddlCats = new SelectList(cats, "Id", "Name", cats[0].Name);
ViewData["ddlCats"] = ddlCats;
return View();
}
[HttpPost]
public JsonResult GetSubcategories(long catId)
{
var subCat = DB.Subcategory.FindSubcategories(catId);
return Json(subCat);
}
}
Here is my View:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$('#ddlCats').change(function () {
$.ajaxSetup({ cache: false });
var selectedItem = $(this).val();
if (selectedItem == "" || selectedItem == 0) {
//Do nothing or hide...?
} else {
$.post('<%: ResolveUrl("~/Home/GetSubcategories/")%>' + $("#ddlCats > option:selected").attr("value"), function (data) {
var items = "";
$.each(data, function (i, data) {
items += "<option value='" + data.ID + "'>" + data.Name + "</option>";
});
$("#ddlsubCats").html(items);
$("#ddlsubCats").removeAttr('disabled');
});
}
});
});
</script>
<div>
<div>
<h2>
Choose category:
</h2>
<%:Html.DropDownList("ddlCats", (SelectList) ViewData["ddlCats"]) %>
</div>
<div>
<h2>
and subcategory:
</h2>
<select id="ddlsubCats" name="ddlsubCats" disabled="disabled">
</select>
</div>
</div>
</asp:Content>
I'm using: jquery-1.5.1.min.js and jquery-ui-1.8.11.custom.min.js.
Many thanks for any advice.
Try like this:
// TODO: make sure that the selectedItem variable represents a valid integer
// as the GetSubcategories expects it as argument:
var selectedItem = $(this).val();
if (selectedItem == "" || selectedItem == 0) {
//Do nothing or hide...?
} else {
var url = '<%= Url.Action("GetSubcategories", "Home") %>';
$.post(url, { catId: selectedItem }, function (data) {
...
});
}
Note that the GetSubcategories expects a parameter called catId which must be a valid 64 bit integer.

Categories

Resources