Asp.net page methods not getting called - asp.net-4.0

I have a simple example of page method.but its not getting called.the breakpoint at GetDate() function never get hit and always it shows alert as 'Failure'.
aspx page is :
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default13.aspx.cs" Inherits="Default13" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript" >
function btnTest_onclick() {
PageMethods.GetDate(Success, Failure);
}
function Success(data) {
alert("success");
alert(data);
}
function Failure(data) {
alert("failure");
alert(data.toSource());
}
</script>
</head>
<body >
<form id="form1" runat="server" method="post">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" ScriptMode="Debug" >
</asp:ScriptManager>
<%--<input type="button" id="btnSave" value="Save" onclick="btnTest_onclick" />--%>
<asp:Button id="btnSave" runat="server" Text="Save" OnClientClick="btnTest_onclick()"/>
</div>
</form>
</body>
</html>
and the aspx.cs page is:
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;
public partial class Default13 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string GetDate()
{
return "str";
}
}
any suggestions?
Thanks in Advance,

I think issue is because your button is server side control, will suggest you to call PageMethod from html button instead.
Still If you require to do so,Please try following code.
<asp:Button id="btnSave" runat="server" Text="Save" OnClientClick="btnTest_onclick(); return false;"/>

Related

How to set focus for InputRadio / InputRadioGroup in Blazor?

I want to set the focus on the InputRadioGroup but it appears it doesn't have the ElementReference attribute unlike the other Blazor built-in form components. Should I just extend the InputRadioGroup and add the ElementReference or is there another way to set focus on the InputRadio or InputRadioGroup?
You could refer to the sample below to focus on the InputRadio.
Vehicle.cs
namespace BlazorApp1.Model
{
public class Vehicle
{
public string Name { get; set; }
}
}
file1.js
window.jsfunction = { focusElement: function (id) { const element = document.getElementById(id); element.focus(); } }
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>BlazorApp1</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link href="BlazorApp1.styles.css" rel="stylesheet" />
<script src="file1.js"></script>
</head>
<body>
<div id="app">Loading...</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
Index.razor
#inject IJSRuntime js
#page "/"
<div>
<h4> vehicle Selected - #vehicle.Name </h4>
<EditForm Model="vehicle">
<InputRadioGroup #bind-Value="vehicle.Name" >
#foreach (var option in rdOptions)
{
<InputRadio Value="option" id=#option #onfocus="alrt" /> #option <br />
}
</InputRadioGroup>
<br>
<input Id="idPassWord" Type="password" />
<button #onclick="clickOK">Set Focus</button>
</EditForm>
</div>
#code{
BlazorApp1.Model.Vehicle vehicle=new BlazorApp1.Model.Vehicle(){Name = "auto"};
List<string> rdOptions = new List<string> { "car", "bus", "auto" };
private async void clickOK()
{
await Focus("car");
}
private void alrt()
{
Console.WriteLine("Element focused");
}
public async Task Focus(string elementId)
{
await js.InvokeVoidAsync("jsfunction.focusElement", elementId);
}
}
Output:
In the above code example, I am generating the InputRadio on the page which has the OnFocus event. While we try to set the Focus on the InputRadio using the JS code. OnFocus event gets fired and displays the message in a browser console. This proves that InputRadio is getting focused.
Further, you could modify the code as per your own requirements.
After some investigation, seems like the ability to focus for InputRadio/InputRadioGroup was removed due to some prior issues. They now returned the focus after I raised the issue, and it will be included to .NET 7.

Why OnPost is not getting hit without "#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers" in ASP.NET Core version 5.0

I'm using ASP.NET CORE version 5.0, and I'm using razor pages for my web UI. I was having a problem hitting a simple OnPost method with the following structure in HTML:
#page
#model EmptyOne.Web.Pages.SaysHelloModel
#{
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Search</title>
</head>
<body>
<p>Enter the name you wanna say hello two ;)</p>
<form method="post">
Search term:
<input name="nameToHello" />
<input type="submit" />
</form>
#* some logic to say hello if model is not null... *#
</body>
</html>
And this is my page model class:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace EmptyOne.Web.Pages
{
public class SaysHelloModel : PageModel
{
public string guysName { get; set; }
public void OnGet()
{
}
public IActionResult OnPost(string nameToHello)
{
guysName = nameToHello;
return Page();
}
}
}
It returns an HTTP 400 status core and a blank page when I try to hit it, but for some reason, when I add this helper:
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
It works fine!
The final and working view(i didn't change anything in the page model class):
#page
#model EmptyOne.Web.Pages.SaysHelloModel
#{
}
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Search</title>
</head>
<body>
<p>Enter the name you wanna say hello two ;)</p>
<form method="post">
Search term:
<input name="nameToHello" />
<input type="submit" />
</form>
#* some logic to say hello if model is not null... *#
</body>
</html>
So can anyone explain to me why that is? I looked up an ASP.NET Core version 5.0 code example and saw this helper. Am I using this helper in any way? What does it have to do with sending an HTTP post request to my page handler?
Razor Pages includes an anti-CSRF mechanism, known as request verification, by default. It relies on a token that is applied to a hidden form field being sent with each POST request. The hidden form field is generated automatically by the form tag helper. If you omit the token value from your post, for example by disabling the form tag helper, the framework returns a 400 Bad Request.

Razor class library and html helpers problem

I create a small admin tool and I decided to convert it to a Razor class library so that I will be able to use it in other applications as well. I created the Razor Class Library project and I added all the razor pages that I had in my main project and I tried to test the new project. The problem was that the framework for some reason did not recognize the html helpers so I created a new clean project and try to find out what is wrong and the result was that the application did not fire the post action of the razor page and the asp-for property was not using properly the property value. I used the following code in order to test the Razor Class Library.
Page1.cshtml.cs
public class Page1Model : PageModel
{
[BindProperty]
public Input MyInput { get; set; }
public class Input
{
public string Name { get; set; }
}
public void OnGet()
{
}
public void OnPost()
{
}
}
Page1.cshtml
#page
#model WebApplication1.MyFeature.Pages.Page1Model
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Page1</title>
</head>
<body>
<form method="post">
<input asp-for="MyInput.Name" /><br />
<input type="submit" />
</form>
</body>
</html>
The generated html was the following
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Page1</title>
</head>
<body>
<form method="post">
<input asp-for="MyInput.Name" /><br />
<input type="submit" />
</form>
</body>
</html>
As you can see the input for MyInput.Name appears as I typed it the Page1.cshtml file. The right output shoud be the following:
<input type="text" id="MyInput_Name" name="MyInput.Name" value="" /><br />
Do I have to do something in order to make the html helpers work and the OnPost action to be called when a post request occurs?
I found the solution to the problem and I decided to share it with you just in case someone else has the same problem.
In order to make it work I had to add the file _ViewImports.cshtml in the pages folder of the Razor Class Library and add the following line:
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

jquery webcam plugin does not post the captured image

I am using jquery webcam plugin in a MVC4 page. The plugin is here: http://www.xarg.org/project/jquery-webcam-plugin/.
I am using save method on the plugin after capturing the image but it is not posted to the controller action.
This is the cshtml page:
#{
ViewBag.Title = "Index";
}
<!DOCTYPE html>
<html lang="es">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>#ViewBag.Title - Prueba WebCam</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/styles/base")
#Scripts.Render("~/scripts/jquery", "~/scripts/jqueryui", "~/scripts/webcam")
<script type="text/javascript">
$(function () {
$("#camera").webcam({
width: 320,
height: 240,
mode: "save",
swffile: "#Url.Content("~/Scripts/WebCam/jscam_canvas_only.swf")",
onTick: function () { },
onSave: function () { alert('Almacenamiento realizado') },
onCapture: function () { webcam.save("#Url.Action("Save")"); alert('Captura realizada'); },
debug: function () { },
onLoad: function () { }
});
});
function CaptureAndSave() {
webcam.capture();
}
</script>
</head>
<body class="home desytec">
<header>
</header>
<!-- MAIN -->
<div id="main">
<!-- wrapper-main -->
<div class="wrapper">
<!-- headline -->
<div class="clear"></div>
<div id="headline">
<span class="main"></span>
<span class="sub"></span>
</div>
<!-- ENDS headline -->
<!-- content -->
<div id="content">
<div id="camera"></div>
<br /><br /><br />
<input type="button" onclick="CaptureAndSave();" value="Capturar" />
</div>
<!-- ENDS content -->
</div>
<!-- ENDS wrapper-main -->
</div>
<!-- ENDS MAIN -->
<footer>
</footer>
</body>
</html>
And this is the controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Capture.Controllers
{
public class CaptureController : Controller
{
//
// GET: /Capture/
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Save(HttpPostedFileBase file)
{
try
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(Server.MapPath("~/Captures"), pic);
file.SaveAs(path);
return Json(true, JsonRequestBehavior.AllowGet);
}
}
catch
{
}
return Json(true, JsonRequestBehavior.AllowGet);
}
}
}
Save method of the controller get never called and in fact, by using firebug, no POST is done.
By the way. The camera works because I can see the it in the canvas (DIV id = camera).
And OnCapture callback is called after I press the capture button.
Any help on this, please?
Thanks
Jaime
Your Save action is not called because the jscam_canvas_only.swf only contains the "callback" mode. For the full API (so for the "save" mode) you need download and use the jscam.swf.
So change your webcam setup to:
$("#camera").webcam({
//...
swffile: "#Url.Content("~/Scripts/WebCam/jscam.swf")",
//...
});
Now your Save action will be called but the file parameter will be always null, because the jscam.swf send the image data as hexadecimal string in the request body.
The default model binding infrastructure is not handling this so you need to write some additional code:
if (Request.InputStream.Length > 0)
{
string pic = System.IO.Path.GetFileName("capture.jpg");
string path = System.IO.Path.Combine(Server.MapPath("~/Captures"), pic);
using (var reader = new StreamReader(Request.InputStream))
{
System.IO.File.WriteAllBytes(path, StringToByteArray(reader.ReadToEnd()));
}
return Json(true, JsonRequestBehavior.AllowGet);
}
You need to remove the file parameter and access the raw data from the Request.InputStream but because it is a hexadecimal string you need to convert it to a byte[] before saving it.
There is no default conversion built in .NET but SO is full of good solutions:
How do you convert Byte Array to Hexadecimal String, and vice versa?
In my sample I've used this method:
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length/2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hex))
{
for (int i = 0; i < NumberChars; i++)
bytes[i] =
Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16);
}
return bytes;
}

How to refer to a control that exists within an Ajax Tab?

I have a problem with using a script that adds a NiceEdit toolbar to a text area when that text area is within an Ajax tab.
I want to know if I should refer to it in a different way than just the ID.
I mean the ID of that text area, I tried to take the text area outside the Tab Container, it works, but when I return it, it simply doesn't.
<%# Page Language="VB" ValidateRequest ="false" AutoEventWireup="false" CodeFile="tabbedNiceEditt.aspx.vb" Inherits="Client_tabbedNiceEditt" %>
<script src="../nicEdit/nicEdit.js" type="text/javascript"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function() {
new nicEditor({buttonList : ['fontSize','fontFamily','fontFormat','bold','italic','underline','strikethrough','forecolor','bgcolor','removeformat'], iconsPath : '../nicEdit/nicEditorIcons.gif'}).panelInstance('txt');
});
</script>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function pageLoad() {
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<cc1:TabContainer ID="TabContainer1" runat="server">
<cc1:TabPanel ID= "first" runat ="server" >
<ContentTemplate>
<b>Stuff Goes HERE</b>
<br />
<asp:TextBox ID = "txt" name = "txt" runat ="server" TextMode ="MultiLine" Height = "256" Width = "256">
</asp:TextBox>
<br />
<br />
<asp:Button id = "btn" runat ="server" Text = "click" />
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel ID = "second" runat ="server" >
<ContentTemplate>
<b>More Stuff for second tab</b>
</ContentTemplate>
</cc1:TabPanel>
</cc1:TabContainer>
</div>
</form>
</body>
</html>
txt is the server ID of your control, you have to use the client ID :
....panelInstance('<%= txt.ClientID %>');
Basically, the client ID is derived from the server ID and the naming container where your control is, to avoid any naming conflict. When your text area is not in the Ajax Tab, the client ID is the same as the server ID. When you put the text area in the Ajax Tab, it's client ID is different (you can check that by looking at the page source in your browser).
EDIT:
From Maen
I viewed the page in browser, checked
the ID in the page source, it was
"TabContainer1$first$txt", used it
instead of "txt" and the script was
like: panelInstance('<%=
txt.TabContainer1$first$txt %> I got
an error: BC30456: 'TabContainer1' is
not a member of
'System.Web.UI.WebControls.TextBox'.
That's not what I meant : you have to put panelInstance('<%= txt.ClientID %>') in your source code, and asp.net will convert that to panelInstance('TabContainer1$first$txt').
I told you to check the page source in the web browser just to see that the client Id was no longer "txt", but that it was constructed from the server ID and the naming container.