Get POST data in C#/ASP.NET

后端 未结 4 536
刺人心
刺人心 2020-11-27 06:06

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.

相关标签:
4条回答
  • 2020-11-27 06:41

    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.

    0 讨论(0)
  • 2020-11-27 06:44

    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" />
    
    0 讨论(0)
  • 2020-11-27 06:55

    The following is OK in HTML4, but not in XHTML. Check your editor.

    <input type=button value="Submit" />
    
    0 讨论(0)
  • 2020-11-27 07:01

    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.

    0 讨论(0)
提交回复
热议问题