I am passing values to code behind (C#). I had researched a lot and used this code, but it didn't work for me. Below is the code that I used.
I need to pass values in code behind (C#), but using this code I am getting an error near routes.EnableFriendlyUrls(settings); as:
Script:
<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: {values : JSON.stringify({ arr: values })},
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
HTML:
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
Code:
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
//settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
[WebMethod]
public static void test(string[] arr)
{
}
Though I had an error in code behind, I am not getting any error, and I am unable to go to code behind even after putting the break point. I am getting a button when I run this code, and when I click this not happen except the page is getting refreshed each time when I click the button. How can I do this?
Change:
var values = [1, 2, 3];//your array wasn't valid
data: {values : values},//you don't need to stringify the values because we have a valid json syntax
Related
I need this ajax call to run my onpost handler PassPart. It successfully calls it, but my parameter "searchedpart" is always empty. I've also tried passing the parameter directly in my url, like: "?handler=passPart" + "&searchedpart=" + searchedpart , but it's still empty. Lastly, I've tried using "Request.Form[SearchedPart]" in my method to pull the value in, also empty. I've tested that this element is not empty by adding an alert message to my js to confirm, and I see the value being found.
ps. I'm using an EmptyResult because I don't need anything posted back. I simply need it to run through my handler using the parameter.
<form method="post">
<input class="form-control" name="searchedpart" asp-for="PostData.SearchedPart" value="#Model.PostData.SearchedPart" id="searchedpart" />
<button type="submit" id="searchpartbtn" class="btn btn-success btn-sm">Find</button>
</form>
document.getElementById('searchpartbtn').addEventListener('click', PassPart);
var searchedpart = document.getElementById('searchedpart').value;
function PassPart() {
$.ajax({
type: "POST",
url: "?handler=passPart",
dataType: "json",
data: JSON.stringify({ searchedpart: searchedpart }),
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
}
});
}
public ActionResult OnPostPassPart(string searchedpart = "")
{
if (searchedpart != "") {
// Do Things
}
return new EmptyResult();
}
Because searchedpart is already a string type, there is no need to JSON.stringify.And you should write your var searchedpart = document.getElementById('searchedpart').value;code inside your function.
Just change your code as below:
document.getElementById('searchpartbtn').addEventListener('click', PassPart);
function PassPart() {
var searchedpart = document.getElementById('searchedpart').value;
$.ajax({
type: "POST",
url: "?handler=PassPart",
dataType: "json",
data: { "searchedpart": searchedpart },
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
}
});
}
In your background:
public ActionResult OnPostPassPart(string searchedpart)
{
//...
}
Result:
I ended up using the following in my method to get this working:
string part = Request.Form["SearchedPart"];
remove dataType: "json"
Add header token
I can't seem to get this simple function working.
The AJAX call returns success but the function is never being called since the Debug.WriteLine is not showing up. The "Function has been called" alert does pop up. There are no errors in the Chrome console.
I am using ASP.NET Web Forms
The Contact.aspx.cs file:
public partial class Contact : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Debug.WriteLine("Contact Page loaded");
}
[System.Web.Services.WebMethod]
public static string Test(string test)
{
Debug.WriteLine("Input param"+test);
return test;
}
}
In the Contact.aspx file
<button type="button" class="btn btn-info" onclick="ShowTest()">Test</button>
<script type = "text/javascript">
function ShowTest() {
//Tried this also (prefered)
//var res = PageMethods.Test("testMessage");
var testMsg = 'This is the test message';
$.ajax({
type: "POST",
url: "Contact.aspx/Test",
data: JSON.stringify({
test: testMsg
}),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (result) {
alert('It worked! ' + result.d);
},
error: function (result) {
alert('Nope');
}
});
alert("Function has been called");
}
</script>
I have found the solution!
Authentication failed in call webmethod from jquery AJAX
Blockquote
I found the answer
Just comment below line in RouteConfig file
//settings.AutoRedirectMode = RedirectMode.Permanent;
I want to postback on every keypress/textchanged event in textbox but my javascript is not running. Am i missing something...????
My Html textbox is this:
<asp:TextBox ID="Txt_Search" runat="server" AutoCompleteType="Disabled"
onkeypress="Postback();" OnTextChanged="Txt_Search_TextChanged" AutoPostBack="true">
</asp:TextBox>
My Javascript code is this:
function Postback() {
__doPostBack('<%= Txt_Search.ClientID %>', '');
};
My on textchanged event is this:
protected void Txt_Search_TextChanged(object sender, EventArgs e)
{
FolderStructure.Nodes.Clear();
Searchtxt();
}
I create sample projects ASP.NET WebForms and AJAX.
I Suggest you can use AJAX process .NET Generic Handler File. Please you research about Generic Handler file.
Before create Generic Handler file "Search.ashx" and Paste above the code.
public void ProcessRequest(HttpContext context)
{
var search = HttpContext.Current.Request.Form["term"];
//Dummy Data
List<string> searchList = new List<string> { "Red", "Orange", "Ping", "Blue", "White", "Black" };
string result = string.Empty;
if (!string.IsNullOrEmpty(search))
{
searchList = searchList.Where(x => x.ToLower().Contains(search.ToLower())).ToList();
if (searchList != null && searchList.Count() > 0)
{
foreach (var item in searchList)
{
result += "<li>" + item + "</li>";
}
}
}
else
{
result="<li> Not Found </li>";
}
context.Response.ContentType = "text/plain";
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
and Create Your Search Page, YourFile.aspx, my file name Search.aspx.
ASPX Page Code :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication7.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="txtSearch" class="js-search" value="Search" />
<div class="searchResult">
<ul>
</ul>
</div>
</div>
</form>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>
<script>
$(function () {
$(".js-search").on('keyup', function () {
var term = $('.js-search').val();
if (term.length > 2) {
sendSearchRequest({ "term": term });
}
});
function sendSearchRequest(value) {
var datas = $.ajax({
type: "POST",
url: '/Search.ashx',
cache: false,
async: false,
data: value,
success: function (term) {
$('.searchResult').empty();
$('.searchResult').append(term);
}
});
}
});
</script>
</body>
</html>
This example when all three letters entered send ajax request search.ashx file and contains search term and get result on search page.
I hope that helps.
Modify code as below and check
__doPostBack('Txt_Search', '');
here is demo for dynamic search in asp.net.
Your textbox should be:
<asp:TextBox ID="PopertyName" placeholder="Property Name" href="#"
propertyid="" runat="server" class="dropdownAnchor"
autocomplete="off" onkeydown="SearchProperty()"></asp:TextBox>
here we will call a function named searchProperty() onkeydown event.
so, your ajax should be,
function SearchProperty() {
$.ajax({
url: '<%=Page.ResolveUrl("~/Dashboard/NewDashboard.aspx/GetProperty") %>',
data: "{ 'prefix': '" + $("#PopertyName").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
//Your code to bind result that received from your back end.
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
};
these function will call a GetPoprty() method on newDashboard.aspx.cs file.
so my back end method is,
[WebMethod]
public static List<Model.Property> GetProperty(string prefix)
{
// Here you get your text in prefix
}
So, I've searched alot and went through alot of tutorials and even though I do everything exactly as in the tutorial, I just can't seem to get it working. Funny thing is, I have been involved in a project where we used the exact same solution and it worked.
I've got a textbox in my forum where users can search for threads in all categories where I am using ajax to show the result in a div in form of a partial view. This is working.
The problem is that I want the thread subjects that are containing the current search term to show up (in form of a normal string) while the user is typing, but I can't seem to get the implementation of autocomplete right. By the way I am retrieving my information from a MSSQL-database.
This is the javascript that I am using to autocomplete (which is not working) and below that you can see my Ajax-form that I use for the search (that works):
<link href="~/Content/jquery-ui.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui.min.js"></script>
#*Scripts for Ajax to show the partial view in the div with id "partialThreads" at request*#
<script src="~/Scripts/jquery-2.2.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript">
$(function () {
$("#txtSearch").autocomplete({
source: '#Url.Action("GetThreadsBySearch", "Forum")'
});
});
</script>
#using (#Ajax.BeginForm("Threads", new AjaxOptions() { UpdateTargetId = "partialThreads", InsertionMode = InsertionMode.Replace, HttpMethod = "POST" }))
{
#Html.AntiForgeryToken()
<p><strong>Search for thread in all categories</strong></p>
#Html.TextBox("searchTerm", null, new { id = "txtSearch", style = "width: 1000px" })
<input type="submit" value="Search" />
}
Here is the div where I show the results of the search in form of a partial view:
<div id="partialThreads">
</div>
Here is the action method that I am using for my ajax-form search (the working one):
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Threads(string searchTerm)
{
var model = string.IsNullOrWhiteSpace(searchTerm)
? new List<ThreadsListModel>()
: _threadRepo.GetThreadsBySearch(searchTerm).OrderByDescending(x => x.DateCreated).ToList();
return PartialView("_Threads", model);
}
And here is the method that I use to retrieve the information to my autocomplete (I've tried setting a break point on it, it doesn't even break):
public JsonResult GetThreadsBySearch(string term)
{
var threadNames = _threadRepo.GetThreadsBySearch(term).Select(x => x.Subject).ToList();
return Json(threadNames, JsonRequestBehavior.AllowGet);
}
Note that I use the same db-query to search with the form and for the autocomplete (only difference would be that I select the threadnames as a List in the GetThreadsBySearch method. So that can't be the problem (?). Here is query-method in case you want to have a look:
public ICollection<ThreadsListModel> GetThreadsBySearch(string subject)
{
using (var context = new ForumContext())
{
return
context.Threads.Where(x => x.Subject.ToLower().Contains(subject.ToLower()) && x.IsActive)
.Select(x => new ThreadsListModel()
{
ID = x.ID,
DateCreated = x.DateCreated,
CreatedBy = x.CreatedBy,
Subject = x.Subject,
PostsCount = x.Posts.Count
}).Distinct().ToList();
}
}
Also, I am using Visual Studio 2015 (.NET 4.5.2) MVC 5. I hope that I haven't forgot to write down any helpful information.
Your scripts are in the wrong order and jquery needs to be before jquery-ui (and also ensure that you do not have any duplicated scripts)
$("#MainContent_txtCountry").autocomplete({
source: function (request, response) {
var param = { keyword: $('#MainContent_txtCountry').val() };
$.ajax({
url: "Default.aspx/GetCountryNames",
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);
}
});
},
});
I'm creating asp.net mvc 5 application.In that application I want generate a Folder once I click a button on front end view page.
I want to generate that folder with in following location ~/Essential_Folder/
<input type = "button" value="Create_Folder" class="btn btn-default" id="create_folder"/>
How can I do this ,
can I do this using Server side language (in my case its C#), if its how ?
is this possible to do using client side language (such as JavaScript) ?
script
<script type="text/javascript">
$('btn-default').click(function () {
});
</script>
As #Stephen mentioned, you need to use ajax in order to create a folder. So you can have an action method like this:
[HttpPost]
public JsonResult CreateDirectory()
{
//if location has folder called "Essential_Folder" it should allow to goto inside of this if condition
if (Directory.Exists(Server.MapPath("~/Content/Essential_Folder/")))
{
Directory.CreateDirectory(Server.MapPath(string.Format("~/Content/Essential_Folder/NewDir_{0}",
DateTime.Now.Millisecond)));
return Json("OK");
}
return Json("NO");
}
And your ajax call should something like this:
<script type="text/javascript">
$('.btn').click(function() {
$.ajax({
url: "#Url.Action("CreateDirectory")",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
if (response === 'OK')
alert("Directory has been created");
else
alert("errro");
}
});
});
</script>