Get POST data in C#/ASP.NET - c#

I am trying to get POST data, but I'm having no luck. My code is below. When I click the form button nothing happens.
I expected at least my IDE to snap at A.Ret(), but nothing happens whatsoever.
File Test.cs
using System.Web;
public class A
{
public static string ret() {
var c = HttpContext.Current;
var v = c.Request.QueryString; // <-- I can see get data in this
return c.Request.UserAgent.ToString();
return c.Request.UserHostAddress.ToString();
return "woot";
}
}
File Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="aspnetCSone._Default" %>
<!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>
</head>
<body>
<form id="form1" runat="server" method="post" action="Default.aspx">
<input type=hidden name="AP" value="99" />
<input type=button value="Submit" />
<div>
<a id="aa">a</a>
<% = A.ret() %>
</div>
</form>
</body>
</html>

Try using:
string ap = c.Request["AP"];
That reads from the cookies, form, query string or server variables.
Alternatively:
string ap = c.Request.Form["AP"];
to just read from the form's data.

c.Request["AP"] will read posted values. Also you need to use a submit button to post the form:
<input type="submit" value="Submit" />
instead of
<input type=button value="Submit" />

I'm a little surprised that this question has been asked so many times before, but the most reuseable and friendly solution hasn't been documented.
I often have webpages using AngularJS, and when I click on a Save button, I'll "POST" this data back to my .aspx page or .ashx handler to save this back to the database. The data will be in the form of a JSON record.
On the server, to turn the raw posted data back into a C# class, here's what I would do.
First, define a C# class which will contain the posted data.
Supposing my webpage is posting JSON data like this:
{
"UserID" : 1,
"FirstName" : "Mike",
"LastName" : "Mike",
"Address1" : "10 Really Street",
"Address2" : "London"
}
Then I'd define a C# class like this...
public class JSONRequest
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
}
(These classes can be nested, but the structure must match the format of the JSON data. So, if you're posting a JSON User record, with a list of Order records within it, your C# class should also contain a List<> of Order records.)
Now, in my .aspx.cs or .ashx file, I just need to do this, and leave JSON.Net to do the hard work...
protected void Page_Load(object sender, EventArgs e)
{
string jsonString = "";
HttpContext.Current.Request.InputStream.Position = 0;
using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
JSONRequest oneQuestion = JsonConvert.DeserializeObject<JSONRequest>(jsonString);
And that's it. You now have a JSONRequest class containing the various fields which were POSTed to your server.

The following is OK in HTML4, but not in XHTML. Check your editor.
<input type=button value="Submit" />

Related

Get the same display using an ActionLink inside Html.BeginForm and simple <a> tag

In my ASP.NET MVC 5 website I have a menu with two types of files: actual pages returned from the controllers and pdf files that you can view in the navigator. Since my menu is created dynamically (it varies according to Active Directory rights) I have to distinguish which type is which (Document or Page), and this means that according to the file type you click, it will not result in the same action.
To show you, imagine there is a List<DocumentModel> documents and the following to treat the information:
<ul>
#foreach (var document in documents)
{
<li>
#if (document.type.Equals("Document"))
{
using (Html.BeginForm("DisplayPDF", "Navigation", new { pdfName = document.link }, FormMethod.Post))
{
#Html.ActionLink(document.docName, "DisplayPDF", null, new {id="linkStyle", #class = "saveButton", onclick = "return false;" })
}
}
else
{
//This link is different then the one above visually
<span class="glyphicon glyphicon-file"></span>#document.docName
}
</li>
</ul>
<!--This script allows to submit the form, and treat the action of DisplayPDF-->
<script>
$(document).ready(function () {
$('.saveButton').click(function () {
$(this).closest('form')[0].submit();
});
});
</script>
DocumentModel is as follows:
public class DocumentModel
{
public long idDocument { get; set; }
public long idCategory { get; set; }
public string docName { get; set; }
public string link { get; set; }
public string type { get; set; }
}
Finally my DisplayPDF method is the following:
public FileContentResult DisplayPDF(string pdfName)
{
var fullPathToFile = #"Your\Path\Here" + pdfName;
var mimeType = "application/pdf";
var fileContents = System.IO.File.ReadAllBytes(fullPathToFile);
return new FileContentResult(fileContents, mimeType);
}
Now as you can see in the Razor view I displayed, there are two types of clickable links. One is only a controller redirection, whereas the second calls the DisplayPDF method and then returns a PDF page. The problem I'm having is that these links are displayed differently, and I don't know how to have the same display for both.
To synthesize my question : how to display the same using #Html.ActionLink() and 'a' tag, knowing that currently, the 'a' tag has the proper display?
Update I modified some code as to give IDs to <a> tag and #Html.ActionLink, then I added this css in stylesheet:
#linkStyle {
margin-left: 25px;
color: antiquewhite;
}
But I still have a different display
UPDATE 2 I think that the problem of display come from the BeginForm method, any ideas to fix this?

RESTfull web service display info on page, using visual studio 2015

I have trouble with building a web service can read information of NBA players from a txt file and then display it on the web page.
Firstly, I build a class in the Models folder.
namespace zuoye4.Models
{
public class Players
{
public string Registration_ID { get; set; }
public string Player_name { get; set; }
public string Team_name { get; set; }
public DateTime Date_of_birth { get; set; }
}
}
Secondly I create a Controller to read file and add all players to an list. I also define a GetAllPlayers method to return the list.
Testing shows this
Then I create a html page to display the list. Here is my code.
<!DOCTYPE html>
<html>
<head>
<title>PLALYERS</title>
<meta charset="utf-8" />
</head>
<body>
<div>
<h2>All Players</h2>
<ul id="players" />
</div>
<div>
<h2>Search by ID</h2>
<input type="text" id="prodId" size="5" />
<input type="button" value="Search" onclick="find();" />
<p id="product" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/Players';
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of players.
$.each(data, function (key, item) {
// Add a list item for the player.
$('<li>', { text: formatItem(item) }).appendTo($('#playerList'));
});
});
});
function formatItem(item) {
return item.Registration_ID + ': $' + item.Player_name;
}
</script>
</body>
</html>
It should shows something like this.
But I get nothing.
What I've done wrong???
Here is the tutorial follow.
https://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
You seem to be appending the players list item to an element with id "playerList":
$('<li>', { text: formatItem(item) }).appendTo($('#playerList'));
Problem is, "playerList" doesn't seem to exist, I see you have a "players" instead?
<ul id="players" />

Reading rss2 feed using C# ASP.NET content:encoded tag

I am trying to read a rss2 feed from a Word Press blog. I have found examples of this, including the one I adapted for my code here. The problem is that it does not read the content:encoded tag. I have searched and found other people that have had this problem, but nothing where it seems to have been solved.
I am using a repeater on an asp.net page with C# code behind to display the data.
The problem seems to be that the content:encoded tag is not defined in http://purl.org/dc/elements/1.0/modules/content/ I've checked it's not listed there at all. When I set a breakpoint and check the value the "content" is actually getting the value of another tag: "{0}" is the value in it after the first post is read into the post object. Although it is never displayed in the repeater.
I assume that content must have been defined at that URL at one time, because this supposedly worked at one time. But it does not now.
Short of reading the XML as a string and re-inventing the wheel to read the tags is there a known way to solve this? Is there a link I can supply that will define the content tag for the code to use? (I am assuming that is the purpose of the URLS). Could I just create my own page with a definition?
Here is the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Load the blog posts
string sURL1 = "http://www.stellman-greene.com/feed";
string sURL2 = "http://arnottsuspension.com/?feed=rss2";
XDocument ourBlog = XDocument.Load(sURL2);
// Query the <item>s in the XML RSS data and select each one into a new Post()
IEnumerable<Post> posts =
from post in ourBlog.Descendants("item")
select new Post(post);
postRepeater.DataSource = posts;
postRepeater.DataBind();
}
class Post
{
public string Title { get; private set; }
public DateTime? Date { get; private set; }
public string Url { get; private set; }
public string Description { get; private set; }
public string Creator { get; private set; }
public string Content { get; private set; }
private static string GetElementValue(XContainer element, string name)
{
if ((element == null) || (element.Element(name) == null))
return String.Empty;
return element.Element(name).Value;
}
public Post(XContainer post)
{
// Get the string properties from the post's element values
Title = GetElementValue(post, "title");
Url = GetElementValue(post, "guid");
Description = GetElementValue(post, "description");
Creator = GetElementValue(post,
"{http://purl.org/dc/elements/1.1/}creator");
Content = GetElementValue(post,
"{http://purl.org/dc/elements/1.0/modules/content/}encoded");
// The Date property is a nullable DateTime? -- if the pubDate element
// can't be parsed into a valid date, the Date property is set to null
DateTime result;
if (DateTime.TryParse(GetElementValue(post, "pubDate"), out result))
Date = (DateTime?)result;
}
public override string ToString()
{
return String.Format("{0} by {1}", Title ?? "no title", Creator ?? "Unknown");
}
}
}
Here is the HTML/ASP:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="postRepeater" runat="server">
<ItemTemplate>
<tr>
<td><%# Eval("Title") %></td><br />
</tr>
<tr>
<td><%# Eval("Description") %></td><br />
</tr>
<tr>
<td><%# Eval("Content") %></td><br />
</tr>
<tr>
<td>Read More</td><br /><br />
</tr>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
I found the correct namespace (If that is the correct term to use for this.
Where I had:
http://purl.org/dc/elements/1.0/modules/content/
I replaced it with:
http://purl.org/rss/1.0/modules/content/
And it now works.

Why DataBinding can't find a property which exist?

I have declared a class but when I try to access it's members I get the following error :
DataBinding: 'reapTest.Toop' does not contain a property with the name 'Rang'.
WebForm1.aspx.cs :
namespace reapTest {
public class Toop {
public string Rang;
public int Gheymat;
}
public static class MyData {
public static Toop[] TP = new Toop[] { new Toop() { Rang = "Ghermez", Gheymat = 100 }, new Toop() { Rang = "Yellow", Gheymat = 44 } };
public static Toop[] RT() {
return TP;
}
}
public partial class WebForm1 : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
}
}
}
WebForm1.aspx :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="reapTest.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1">
<ItemTemplate>
<%#Eval("Rang")%>
</ItemTemplate>
</asp:Repeater>
<asp:ObjectDataSource runat="server" ID="ObjectDataSource1" SelectMethod="RT" TypeName="reapTest.MyData"></asp:ObjectDataSource>
</div>
</form>
</body>
</html>
I believe it is because it is looking for a literal property named Rang. You have a field named Rang, but that's not the same as a property, to-wit:
EDIT: Code sample
public class Toop {
// These values are *fields* within the class, but *not* "properties."
private string m_Rang; // changing these field decls to include m_ prefix for clarity
private int m_Gheymat; // also changing them to private, which is a better practice
// This is a public *property* procedure
public string Rang
{
get
{
return m_Rang;
}
set
{
m_Rang = value;
}
}
}
Fields and Properties are related in that Properties provide a public "wrapper" mechanism to the "private" field data of each instance of the class. But it is critical to note that they are separate concepts, and not interchangeable. Merely having a field declaration (also called a member in some object parlance) does not expose it as a property. Note what #FrédéricHamidi said - the docs state the "value of the expression parameter must evaluate to a public **property**"(emphasis mine).
As noted in this excerpt directly from Microsoft, EVAL, one way or the other, has to have a property.
Hopefully that helps.

how to call a variable in code behind to aspx page

i know i have seen this but cant recall the correct way of doing it... basically i have a string variable called "string clients" in my .cs file.. but i wasn't to be able to pass it to my aspx page something like
<%=clients%>
please correct me, i do not recall or not sure how to do this. (new to c#) and when i googled it.. it was not clear.. or not many of these out there.. searched as
"asp.net c# <%= %> not consistent results.. maybe because i do not know how to call these..
The field must be declared public for proper visibility from the ASPX markup. In any case, you could declare a property:
private string clients;
public string Clients { get { return clients; } }
UPDATE: It can also be declared as protected, as stated in the comments below.
Then, to call it on the ASPX side:
<%=Clients%>
Note that this won't work if you place it on a server tag attribute. For example:
<asp:Label runat="server" Text="<%=Clients%>" />
This isn't valid. This is:
<div><%=Clients%></div>
In your code behind file, have a public variable
public partial class _Default : System.Web.UI.Page
{
public string clients;
protected void Page_Load(object sender, EventArgs e)
{
// your code that at one points sets the variable
this.clients = "abc";
}
}
now in your design code, just assign that to something, like:
<div>
<p><%= clients %></p>
</div>
or even a javascript variable
<script type="text/javascript">
var clients = '<%= clients %>';
</script>
For
<%=clients%>
to work you need to have a public or protected variable clients in the code-behind.
Here is an article that explains it:
http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
Make sure that you have compiled your *.cs file before browsing the ASPX page.
First you have to make sure the access level of the variable is protected or public. If the variable or property is private the page won't have access to it.
Code Behind
protected String Clients { get; set; }
Aspx
<span><%=Clients %> </span>
You need to declare your clients variable as public, e.g.
public string clients;
but you should probably do it as a Property, e.g.
private string clients;
public string Clients{ get{ return clients; } set {clients = value;} }
And then you can call it in your .aspx page like this:
<%=Clients%>
Variables in C# are private by default. Read more on access modifiers in C# on MSDN and properties in C# on MSDN
You can access a public/protected property using the data binding expression <%# myproperty %> as given below:
<asp:Label ID="Label1" runat="server" Text="<%#CodeBehindVarPublic %>"></asp:Label>
you should call DataBind method, otherwise it can't be evaluated.
public partial class WebForm1 : System.Web.UI.Page
{
public string CodeBehindVarPublic { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
CodeBehindVarPublic ="xyz";
//you should call the next line in case of using <%#CodeBehindVarPublic %>
DataBind();
}
}
I would create a property to access the variable, like this:
protected string Test
{
get; set;
}
And in your markup:
<%= this.Test %>
The HelloFromCsharp.aspx look like this
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="HelloFromCsharp.aspx.cs" Inherits="Test.HelloFromCsharp" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<p>
<%= clients%>
</p>
</form>
</body>
</html>
And the HelloFromCsharp.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Test
{
public partial class HelloFromCsharp : System.Web.UI.Page
{
public string clients;
protected void Page_Load(object sender, EventArgs e)
{
clients = "Hello From C#";
}
}
}

Categories

Resources