I am trying a simple task of displaying student name in a textbox based on StudentId entered. I am able to display the student name as an alert from jQuery - AJAX call but not in the text box, what am I missing here?
Controller:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult DisplayStudentName(string id)
{
StudentDataContext db = new StudentDataContext();
var StudentName = (from p in db.vwStudents.Where(a => a.StudentNumber == id)
group p by p.StudentName into g
select g.Key).FirstOrDefault();
return Json(new { Name = StudentName });
}
jQuery:
$(function () {
$('#submitButton').click(function () {
var link = '/StudentForm/DisplayStudentName';
$.ajax({
type: 'POST',
url: link,
data: { id: $('#id').val() },
dataType: 'json',
success: function (result) {
$("#StudentName").val(result.Name);
alert(result.Name);
},
error: function (result) {
alert("Failed")
}
});
});
});
View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Student Form
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="Data" style="text-align: left; height: 202px;">
Student Number:<input type="text" name="id" id="id"/><br />
Student Name:<input type="text" name="StudentName" id="StudentName"/><br />
<br />
<div id="Div1">
<button id="submitButton" name="submitButton" style="width:140px;">Display Short Name</button>
</div>
</div>
</asp:Content>
Again, I am able to display Student Name in the Alert window, but not in the text box, Am I missing something?
Thanks in advance
You need to prevent the default behavior of submit button. You can use the jQuery preventDefault function to do this,
$(function () {
$('#submitButton').click(function (e) {
e.preventDefault(); //prevent default behaviour
var link = '/StudentForm/DisplayStudentName';
$.ajax({
type: 'POST',
url: link,
data: { id: $('#id').val() },
dataType: 'json',
success: function (result) {
$("#StudentName").val(result.Name);
},
error: function (result) {
alert("Failed")
}
});
});
})
When preventDefault method is called, the default action of the event will not be triggered. So in this case the form submission will not happen ( so the page wont be reloaded).
Related
I have to pass bulk array values to code behind (cs) using ajax i had researched a lot and used this code but it didnot worked for me below is the code that i used what i need is i need to pass bulk array values in code behind(cs) using ajax
JS
<head runat="server">
<title></title>
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
</body>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace PassingValueFromJavascriptToCs
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void done(string[] ids)
{
String[] a = ids;
// Do whatever processing you want
// However, you cannot access server controls
// in a static web method.
}
}
}
First of all the button for aspx is sending your aspx form to a postback so that you would need to change the aspx like this
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
</body>
The reason the foo method returns false that you dont want to make your button start a postback. I also added another property UseSubmitBehavior="false" to guarantee it.
The scripts section i changed the values object to a real array and then when sending data , i converted it to json with values object inside. This code will work in your example just fine
Edit : For the working version on my tests
The aspx page (trimmed details to the master page)
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script>
function test() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/test", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
debugger;
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
<asp:Button ID="Button3" UseSubmitBehavior="false" OnClientClick="return test();" runat="server" Text="Deneme" />
</asp:Content>
The RouteConfig and original method
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
//settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
[WebMethod]
public static void test(string[] arr)
{
}
Well at least one issue is your url is "Default.aspx/Done" but the method appears to be on WebForm3.aspx/Done.
What actually happens with your code? Does it error?
I want to display an image immediately after fill the textbox, don't need to click any button for get the picture.
I did this in my view:
#using (Html.BeginForm())
{
<input value="" id="UserID" name="UserID" type="text" class="form-control" />
<img id="CaptchaImg" alt="Captcha" src="#Url.Action("showFoto", "loan")" style="" />
}
<script language="javascript" type="text/javascript">
$.ajax({
type: "POST",
url: '#Url.Action("showFoto", "loan")',
datatype: "image/jpg",
success: function (UserID) {
$('#CaptchaImg').attr('src', UserID);
}
});
</script>
In my controller Loan.cs:
[HttpPost]
public string showFoto(string UserID)
{
string ImageID = UserID;
var virtualPath = string.Format("~/images/profile/{0}.jpg", ImageID);
if (System.IO.File.Exists(Server.MapPath(virtualPath)))
{
return virtualPath;
}
return null;
}
My information was from:get a image through jquery ajax
Please, need your helps... thanks!
Change your script to handle the .change event of the textbox and pass its value to the sever method (note the change event occurs when the textbox loses focus)
$('#UserID').change(function() {
$.ajax({
type: "GET",
url: '#Url.Action("showFoto", "loan")',
data: { userID: $(this).val() }, // pass the value of the textbox to the method
datatype: "image/jpg",
success: function (UserID) {
$('#CaptchaImg').attr('src', UserID);
}
});
});
To whom it may respond to,
We are trying to insert the data to Oracle DBMS, fetched by JSON by calling asp.net webservices.
Here,aspx page is the modified code from another stackoverflow answer. Do we have to use JSON again to send the values to codebehind ? If so, how?
Thanks to http://www.codingfusion.com/Post/Jquery-JSON-Add-Edit-Update-Delete-in-Asp-Net for sample scripts
Thank you for your concern
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="test7._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
<Scripts>
<asp:ScriptReference Path="Scripts/jquery-1.11.1.min.js" />
<asp:ScriptReference Path="Scripts/jquery-ui.min.js" />
</Scripts>
</asp:ScriptManagerProxy>
<div id="outer" style="width: 100%; background-color: #737CA1">
<div id="HeadDiv" style="width: 90%; background-color: #737CA1">
<script type="text/javascript" id="ButceList">
$(function () {
$("#txtButce").autocomplete({
source: function (request, response) {
var param = { prefixText: $('#txtButce').val() };
$.ajax({
url: "Default.aspx/GetButce",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2//minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data.
});
});
</script>
<script type="text/javascript" id="TipList">
$(function () {
$("#txtTip").autocomplete({
source: function (request, response) {
var param = { prefixText: $('#txtTip').val() };
$.ajax({
url: "Default.aspx/GetTip",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2//minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data.
});
});
</script>
<script type="text/javascript">
function openModalForm() {
window.showModalDialog('Details.aspx', '', 'status:1; resizable:1; dialogWidth:900px; dialogHeight:500px; dialogTop=50px; dialogLeft:100px')
}
</script>
<script type="text/javascript">
function saveData() {
//==== Call validateData() Method to perform validation. This method will return 0
//==== if validation pass else returns number of validations fails.
//var errCount = validateData();
//==== If validation pass save the data.
var txtButce = $("#txtButce").val();
var txtTip = $("#txtTip").val();
$.ajax({
type: "POST",
url: "Default.aspx/saveData",
data: JSON.stringify({butce:txtButce,tip:txtTip}),
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
$(".errMsg ul").remove();
var myObject = eval('(' + response.d + ')');
if (myObject > 0) {
$(".errMsg").append("<ul><li>Data kaydedildi</li></ul>");
}
else {
$(".errMsg").append("<ul><li>Kayıt işleminde hata olustu, tekrar deneyiniz.</li></ul>");
}
$(".errMsg").show("slow");
clear();
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
</script>
<div class="ui-widget">
<label for="txtButce" >Bütçe Kodu/Lokasyon: </label>
<input id="txtButce">
<br />
<label for="txtTip">Tip/Alttip: </label>
<input id="txtTip" />
</div>
<asp:Label ID="lblDateInfo" runat="server" Style="color: White;" /><br />
<asp:Button ID="btnCalShow" runat="server" Text="Tarih Seçiniz" />
<asp:Button ID="btnShow" runat="server" Text="Show Modal Popup" />
</div>
<br />
<asp:Button ID="btnPenaltyCalculate" Text="Hesapla" runat="server" Style="margin-left: 0px; margin-top: 5px; margin-bottom: 5px;" />
<asp:Button ID="btnPenaltySubmit" Text="Kaydet" runat="server" Style="margin-left: 5px; margin-top: 5px; margin-bottom: 5px;" />
<%-- %> <asp:Button ID="btnRefresh" runat="server" Text="Haftayı yeniden yükle" style="margin-left:60px;margin-top:5px;margin-bottom:5px;" />
--%>
</div>
</asp:Content>
You will need to do another AJAX POST to a WebMethod (or asp.net postback) to send the data back to the server which can then update your database.
I have a website where I display student info. I want to add few text fields on the website and update those fields asynchronously using jQuery(Ajax) on Button click. I believe I have all the requirements in place but the data is still not updated.
Am I missing something here? Clicking buttons does nothing.
Here is my Code -
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Student.Models;
namespace Student.Controllers
{
public class StudentController : Controller
{
public ActionResult Index()
{
return View("Student");
}
[HttpPost()]
public ActionResult DisplayStudentName(string id)
{
StudentDataContext db = new StudentDataContext();
var StudentName = (from p in db.vwStudent.Where(a => a.StudentId == id)
group p by p.StudentName into g
select g.Key).FirstOrDefault();
ViewData["StudentName"] = StudentName;
return View("Student");
}
[HttpPost()]
public ActionResult DisplayStudentStatus(int? id, string flg)
{
AccountDataContext db = new AccountDataContext();
var StudentStatus = (from p in db.vwStudent.Where(a => a.StudentId == id && a.LastFlag == flg)
group p by p.Status into g
select g.Key).FirstOrDefault();
ViewData["StudentStatus "] = StudentStatus;
return View("Student");
}
}
}
jQuery:
$("#Button1").click(function() {
var link = '<%= Url.Action("DisplayStudentName", "Student")';
$.ajax({
url: link,
data: "{id: '<%= ViewContext.RouteData.Values["id"] %>'}",
dataType: "html",
success: Success,
error: Fail
});
});
$("#Button2").click(function() {
var link = '<%= Url.Action("DisplayStudentStatus", "Student")';
$.ajax({
url: link,
data: "{id: '<%= ViewContext.RouteData.Values["id"] %>' ,
flg: '<%= ViewContext.RouteData.Values["flg"] %>'}",
dataType: "html",
success: Success,
error: Fail
});
});
function Success(){
alert("Success");
}
function Fail(){
alert("Fail");
}
View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Student Form
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form id="form1" method="get" runat="server">
Student ID:<input type="text" name="id" id="StudentId" value="<%=HttpContext.Current.Request.QueryString["id"]%>" /><br />
Student Name:<input type="text" name="StudentName" id="StudentName" value="<%=ViewData["StudentName"]%>"/>
<div id="Btn1"><input type="button" value="Display Student Name" name="Btn1" id="Button1" />
</div>
Student Status:<input type="text" name="StudentStatus" id="StudentStatus" value="<%=HttpContext.Current.Request.QueryString["StudentStatus"]%>" />
<div id="Btn2"><input type="button" value="Display Profit Center" name="Btn2" id="Button2" />
</div>
</div>
</form>
</asp:Content>
Thanks in advance
There are a couple of issues with your code that I see:
You should not wrap the data parameters into single quotes.
Your success and error parameters should not be strings. They should be functions
You should never hardcode urls in an ASP.NET MVC application. You should always use url helpers when dealing with urls
So:
$("#Button1").click(function() {
var link = '<%= Url.Action("DisplayStudentName", "Student")';
$.ajax({
url: link,
data: { id: '<%= ViewContext.RouteData.Values["id"] %>' },
success: Success,
error: Fail
});
});
$("#Button2").click(function() {
var link = '<%= Url.Action("DisplayStudentStatus", "Student")';
$.ajax({
url: link,
data: {
id: '<%= ViewContext.RouteData.Values["id"] %>' ,
flg: '<%= ViewContext.RouteData.Values["flg"] %>'
},
success: Success,
error: Fail
});
});
where obviously you must have declared the 2 functions used:
function Success(data) {
// ...
}
function Fail() {
// ...
}
need to mention post in ur ajax parameters
$.ajax({
url: link,
type: 'post',
Also you have mentioned json as the datatype in your ajax function but your action is returning text/html.
Make these 2 changes and if it doesnt work then check fiddler to see what response you are getting from the server.
If you are getting a valid response then check your success function to see if you are doin things right.
If you want to support get and post scenarios on your action then change the attribute on your action to
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
I have 2 dropdownlist which is already binded on pageload , i want to rebind these two dropdownlist after firing a ajax function.Here i have written a sql server stored procedure to get the data which is needed to dropdownlists.But how i will get the value to dropdownlist,so that it can bind the new data using ajax function.The screen is developed by using Asp.net C# coding.
Here is the drop down list of the asp.net
<asp:DropDownList id="ddlCourse" runat="server" AutoPostBack="false"
Height="28px" title="Select Course" Width="290px"
></asp:DropDownList>
and here is the jquery method that is calling the web service method
function BindCourse() {
$.ajax({
type: "POST",
url: "/WebService/CollegeWebService.asmx/GetCourseDetails",
data: "{}",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnCoursePopulated,
error: function (xml, textStatus, errorThrown) {
alert('error');
alert(xml.status + "||" + xml.responseText);
}
});
}
This is the method to That is used in the ajex call method and call the PopulateControl method to bind the Drop down List
function OnCoursePopulated(response) {
PopulateControl(response.d, $('#<%=ddlCourse.ClientID %>'));
}
Here is the description of the PopulateControl Method
function PopulateControl(list, control) {
if (list.length > 0) {
control.removeAttr("disabled");
control.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(list, function () {
control.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
else {
control.empty().append('<option selected="selected" value="0">Not available<option>');
}
}
Thus you finally bind the drop down list
You can try the following as a demo. Server side DropDownLists are replaced with HTML select elements so that exception "Invalid postback or callback argument" doesn't happen.
Drawback in this demo is that the values are not restored on form after postback. You can put this inside a form in Default.aspx:
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function populate(populateInitial) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/Default.aspx/populate',
data: "{'populateInitial': '" + populateInitial + "'}",
dataType: "json",
async: false,
success: function(result) {
var ddlItems = document.getElementById('ddlItems');
ddlItems.options.length = 0;
$.each(result.d, function(key, item)
{ ddlItems.options[key] = new Option(item); });
}
});
}
</script>
<form id="form1" runat="server">
<div>
<select id="ddlItems" name="ddlItems">
</select>
<br />
<input type="button" onclick="populate('0');" value="Change values" />
<br />
Selected item:
<asp:Label ID="lblSelectedItem" runat="server" Text=""> </asp:Label>
<br />
<asp:Button ID="Button1" runat="server"
Text="Write out selected item text" />
</div>
<script type="text/javascript">
populate('1');
</script>
And you put these methods inside Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
lblSelectedItem.Text = Request["ddlItems"].ToString();
}
}
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static List<string> populate(string populateInitial)
{
if (populateInitial == "1")
return (new string[] { "a", "b" }).ToList();
else
return (new string[] { "c", "d", "e", "f" }).ToList();
}
You should make Ajax call to some sort of page (I advice you to add Generic Hanlder) which responses xml or json or even html, of drop down values and textfield values, than read it in javascript jquery and generate html for your drop down which is the following
<select id="ddl">
<option value="value">text</option>
</select>
you should read "value" & text and generate this> <option value="value">text</option>
and append to ddl