Trying to display 4 concate item in dropdownlist from database - javascript

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.

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.

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.
}
})

Why I cannot Login the using c# and mysql in ASP.net

I am beginner in developing a website using ASP.Net
Please Help me. so that i can pursue my career. Thanks in Advance
I am creating a login script using c# and I want to call it in javascript.
But it after I Logged in, The Login page will only refreshing.
And there is an exception said Exception thrown: 'System.InvalidOperationException' in System.Web.Extensions.dll
So here is my code :
HTML
<form>
<div class="form-group">
<input type="text" class="form-control material" id="username" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control material" id="password" placeholder="Password">
</div>
<button type="submit" id="btnLogin" class="btn btn-block btn-info text-uppercase waves">Login</button>
</form>
JAVASCRIPT:
$(document).ready(function () {
$("#btnLogin").click(function () {
var username = $("#username").val();
var password = $("#password").val();
AuthenticateUser(username, password)
});
});
function AuthenticateUser(username, password) {
var value = "{'email':'" + username
+ "','pass':'" + password
+ "'}";
$.ajax({
type: 'POST',
url: '../WebService/csLogin.asmx/loadEmployeeAccount',
dataType: 'json',
data: value,
contentType: 'application/json; charset=utf-8',
success: function (response) {
var cells = eval("(" + response.d + ")");
console.log(cells);
if (cells.length >= 1) {
window.location.href = "index.html";
} else {
alert("Invalid Email/Password");
document.getElementById("username").focus();
}
},
error: function (error) {
alert(JSON.stringify(error))
}
});
}
C#:
[WebMethod]
public string loadEmployeeAccount(string email, string pass)
{
List<Auth> mylist = new List<Auth>();
using (MySqlConnection connection = new MySqlConnection(connectionString()))
{
connection.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM user WHERE username = #email AND password = #pass", connection);
cmd.Parameters.Add("#email", MySqlDbType.VarChar).Value = email;
cmd.Parameters.Add("#pass", MySqlDbType.VarChar).Value = pass;
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 0;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
int user = 0;
if (dr["userType"].ToString() == "")
user = 1;
else
user = Convert.ToInt32(dr["userType"].ToString());
mylist.Add(new Auth
{
user_id = dr["user_id"].ToString(),
username = dr["username"].ToString()
});
}
dr.Close();
connection.Close();
}
JavaScriptSerializer jss = new JavaScriptSerializer();
string jsn = jss.Serialize(mylist);
return jsn;
}
And here is the image on the console.
Can someone help me with this?? any help will much be appreciated. Thanks
Okay, in order to achieve your functionality follow these steps:
In your AJAX, do the following to convert your value string as JSON and then send it to your WebMethod:
data: {"json": JSON.stringify(value)}
Then decorate your class with:
[System.Web.Script.Services.ScriptService]
to allow POST requests via AJAX to your WebMethod.
And then in your WebMethod, do the following to parse your JSON string that you received from your AJAX call:
[WebMethod]
public string loadEmployeeAccount(string json)
{
dynamic jsondata = serializer.Deserialize(json, typeof(object));
string username = jsondata["email"];
string password=jsondata["pass"]
//Your code here
}
it seems there is issue in passing value from ajax call please make change in your javascript function to call webmethod
function AuthenticateUser(username, password) {
var value = {'email':username,
'pass':password};
$.ajax({
type: 'POST',
url: '../WebService/csLogin.asmx/loadEmployeeAccount',
dataType: 'json',
data: JSON.stringify(value),
contentType: 'application/json; charset=utf-8',
success: function (response) {
var cells = eval("(" + response.d + ")");
console.log(cells);
if (cells.length >= 1) {
window.location.href = "index.html";
} else {
alert("Invalid Email/Password");
document.getElementById("username").focus();
}
},
error: function (error) {
alert(JSON.stringify(error))
}
});
}
I’m not familiar with pure ASP.NET, as I use MVC, but I guess they’re just the same under the hood, so this is a wild guess.
First thing, within your Ajax function you have to change the type of action from POST to GET, your error webpage is explicitly telling you you’re not supposed to send data through a POST action, after all.
type: ‘GET’
Second thing, i think the way you’re passing data to the web method is wrong: you’re passing a single literal object when your method is expecting two strings. By changing this, things should work as expected:
data: {
email: username,
pass: password
}
also, delete the dataType: ‘JSON’

Reload div fires constantly without event MVC

I am working on a project in Visual studio using MVC. I am trying to reload a div after a btn is clicked and data has been posted to the controller dynamically. I use an Ajax post and return a JSONresult. The code for posting looks like this:
<div id = "DelUser">
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "Dform" }))
{
<label> Select User(s) to Delete: </label>
#Html.ListBox("Users", ViewBag.Users as MultiSelectList,
new { #class = "chzn-select", #style = "width:250px; height:350 px" })
}
<button class="btn btn-primary dropdown-toggle" id="Button1" type="button" onclick="DeleteUsers()"> Delete Selected </button>
</div>
<script>
function DeleteUsers() {
var myList = []
$("#Users > option:selected").each(function () {
myList.push($(this).val());
});
jQuery.ajax({
type: 'post',
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: 'DeleteU',
data: JSON.stringify(myList),
success: function (data) {
$('#msgbx2').html(data.msg);
//here I am trying to refresh the div after the post but it fires every second
$('#DelUser').html('/Home/DeleteUser');
},
failure: function (errMsg) {
$('#msgbx2').html(data.msg);
}
});
return false;
}
The name of the controller is DeleteUser and the JSONresult controller is DeleteU.
I am trying to do this so that the dropdownlist updates after I delete the selected users. If there is another way to dynamically update this div, any information on that would be good to know too. Thank you in advance.
Here are the Controllers as well:
[HttpGet]
public ActionResult DeleteUser()
{
List<string> u = new List<string>();
object[] users = data.getDataFrmDB("Select username From `users`;");
if (users != null)
{
foreach (object[] user in users)
{
u.Add((string)user[0]);
}
}
ViewBag.Users = new MultiSelectList(u, "Username");
return View();
}
[HttpPost]
public JsonResult DeleteU(List<string> Users)
{
bool good = false;
if (Users != null)
{
foreach (string user in Users)
{
string ins = "DELETE FROM `xcal-server`.`users` WHERE username='"+user+"';";
good = data.insert_update_delete_DB(ins);
List<string> u = new List<string>();
object[] users = data.getDataFrmDB("Select username From `users`;");
if (users != null)
{
foreach (object[] usera in users)
{
u.Add((string)usera[0]);
}
}
ViewBag.Users = new MultiSelectList(u, "Username");
if (good == true)
{
ViewBag.error = "You have successfully deleted user";
}
else
{
ViewBag.error = "There was an issue removing user";
}
}
return Json(new { msg = "You have Successfully deleted Users " });
}
return Json(new { msg = "the passwords entered do not match" });
}
This is just a section of my main page that has other action functions/controllers in it which is why i did not originally post the controllers
You can simply update the existing listbox by removing the currently selected items. Start by removing onclick="DeleteUsers() from the button and use Unobtrusive JavaScript. Since you do not appear to have a POST method for DeleteUser() or a submit button, you may as well also replace #using (Html.BeginForm(...)) with just <form> elements. The script will then be
$('#Button1').click(function () {
var selected = $('#Users option:selected'); // store the selected users
if (selected.length == 0) {
return; // no point making a post
}
var users = [];
$.each(selected, function (index, item) {
users.push($(this).val());
})
$.ajax({
type: 'post',
dataType: 'json',
url: '#Url.Action("DeleteU", "yourControllerName")', // always use Url.Action to generate your url's
data: { users: users },
traditional: true,
success: function () {
// remove the currently selected options
selected.remove();
}
});
})
However a lot of the code in your controller does not make sense. Your adding values to ViewBag and even creating a SelectList but your not returning a view (your returning json), so all that is lost. And even if you were returning a view, your loop keeps overwriting the value of ViewBag.error so that only the last value would be set. Ideally, you should be calling a service to delete the users by passing the user name (or a collection of user names so that they are all deleted in a transaction). But based on you current code, you controller method can be
[HttpPost]
public JsonResult DeleteU(List<string> Users)
{
if (Users == null)
{
// throw an error that can be caught in the ajax error handler
}
List<string> deletedUsers = new List<string>();
foreach (string user in Users)
{
string ins = "DELETE FROM `xcal-server`.`users` WHERE username='"+user+"';";
if (data.insert_update_delete_DB(ins))
{
deletedUsers.Add(user);
}
}
return Json(deletedUsers);
}
and then the ajax success callback
success: function (data) {
$.each(data, function(index, item) {
// remove each item that was successfully deleted in the controller
$('#Users option:contains("' + item + '")').remove();
}
}
i think you need to add a $(document).ready(function(){}); around your script

How to prevent showing duplicate informations in the sequential time period

I wrote a method (with WebMethod attribute) which give me list of books :
public struct BOOK
{
public string BOOK_NAME;
public string BOOK_DESC;
}
[WebMethod]
public static List<BOOK> GetMyBooks()
{
string _connString = "Data Source=.;Initial Catalog=BookStore;Integrated Security=True";
SqlConnection _conn = new SqlConnection(_connString);
_conn.Open();
SqlCommand _com = new SqlCommand("select * from Book_TBL where IsActive='True' ", _conn);
_com.CommandType = System.Data.CommandType.Text;
SqlDataAdapter bookdataAdapter = new SqlDataAdapter(_com);
DataSet bookDS = new DataSet();
bookdataAdapter.Fill(bookDS, "Book_TBL");
List<BOOK> bookList = new List<BOOK>();
BOOK book;
foreach (DataRow dr in bookDS.Tables["Book_TBL"].Rows)
{
book = new BOOK();
book.BOOK_NAME = dr["book_name"].ToString();
book.BOOK_DESC = dr["book_desc"].ToString();
bookList.Add(book);
}
return bookList;
}
and i wrote a script that call the "GetMyBooks" method every 5 second and show it in a div tag by id:"pejiGrid" in my WebForm2.aspx :
<script>
$(document).ready(function () {
$("#go").click(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "WebForm2.aspx/GetMyBooks",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
for (var i = 0; i < response.d.length; i++) {
$("#pejiGrid").append("<tr><td>" + response.d[i].BOOK_NAME + "</td><td>" + response.d[i].BOOK_DESC + "</td></tr>");
}
}, });
}, 5000);
});
});
but my method and script append duplicate information in my "#pejiGrid", i want to show this information only once, is there any way,which i can do it by script? if it is not possible, what is the solution?
Everything in code is OK. You need just a small correction in your script. Replace the success function body with this code:
var htm = [];
for (var i = 0; i < response.d.length; i++) {
htm.push("" + response.d[i].BOOK_NAME + "" + response.d[i].BOOK_DESC + "");
}
$("#pejiGrid").html(htm.join(''));
If I correctly understood the question the problem was in using the 'append' method of jQuery, which was appending all new data received from server. Instead of that you were needed to replace old data with new one. So you need to use the 'html' method to replace the content of div.
One more advice. It will be better to store methods like 'GetMyBooks()' in web services files, developed specially for that purpose.
Wish you all the best !

Categories

Resources