【问题标题】:Can't add JSON connection in if statement无法在 if 语句中添加 JSON 连接
【发布时间】:2018-08-01 09:38:01
【问题描述】:

我正在网站上工作,我想将数据上传到我在app.aspx.cs中连接的数据库

每次启动应用程序时都会遇到以下错误:

错误 CS0149 方法名称应为 PoshaWeb C:\Users\zatoo\Desktop\Pusha\workweb\PoshaWeb\App.aspx.cs 35 Active

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;

namespace PoshaWeb
{
    public partial class App : System.Web.UI.Page
    {   
        protected void Page_Load(object sender, EventArgs e)
        {

            Stream body = Context.Request.InputStream;
            System.Text.Encoding Encoding = Context.Request.ContentEncoding;
            StreamReader reader = new StreamReader(body, Encoding);
            String inJson = reader.ReadToEnd();
            var s = Newtonsoft.Json.JsonConvert.DeserializeObject(inJson);
            System.Data.SqlClient.SqlConnection Conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["MyPoshDB"].ConnectionString);
            Conn.Open();

            System.Data.SqlClient.SqlCommand Comm = new System.Data.SqlClient.SqlCommand
            {
                Connection = Conn
            };
            try
            {
                if (s("type").ToString = "addstudent")
                {
                    Comm.CommandText = "INSERT INTO Members (MemName, MemMobile, MemEmail, MemID, MemGovID, MemDocURL, MemPicURL) VALUES(N'" + s("name").ToString + "', N'"+ s("mobile").ToString + "', N'" + s("email").ToString + "', N'" + s("recordnumber").ToString + "', N'" + s("idnumber").ToString + "', N'" + s("picturepath").ToString + "', N'" + s("documentpath").ToString + "')";
                    Comm.ExecuteNonQuery();
                    Response.Write("{\"result\":\"success\"}");
                }
            }
            catch (Exception ex)
            {
                Page.Response.Write("{\"result\":\"fail\",\"desc\":" + Newtonsoft.Json.JsonConvert.SerializeObject(ex.Message) + "}");
            }
            Conn.Close();
        }

    }
}

我遇到的问题是变量sif 语句中不起作用。

【问题讨论】:

  • 仅供参考 JSON 中没有 a
  • 还有if (s("type").ToString = "addstudent")应该是if (s("type").ToString == "addstudent")
  • 这整件事有点搞砸了。您不能只写这样的 Web 表单的响应,而不是在 PageLoad 中。很不清楚你想在这里做什么
  • 您还应该阅读using 以及为什么需要使用它。 Memory Leaks C#
  • 考虑使用using 语句来处理您的SqlConnectionSqlCommand - 请参阅stackoverflow.com/questions/75401/…

标签: c# asp.net json if-statement webforms


【解决方案1】:

正如其他人所说,您可以使用提供的链接进行阅读,然后再继续阅读。解决您的问题是因为您使用的是方法组,而不是调用实际的方法调用。

if (s("type").ToString = "addstudent")

应该是

if (s("type").ToString() == "addstudent")

这将解决您遇到的问题,但您的代码中还有更多问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-20
    • 2022-11-18
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多