locked
How to access and perform CRUD to SQL Server Database from a Windows 8 app written in Javascript/HTML through WCF Service? RRS feed

  • Question

  • I have added a new SQL Server Database to the App_Data folder from the sample project below.

    code.msdn.microsoft.com/How-to-consume-JSON-Web-5db0174b#content

    I have added 2 new textbox, 1 button in the HTML for user to enter name, address and a click button to save in database.

    But I don't know how to pass the value entered from the HTML text box, button using WinJS.xhr to the WCF and then perform CRUD from SQL Server database and will display the output in the app.

    default.html

    <input id="txtName" type="text" />
      <input id="txtAddress" type="text" />
      <button id="insertbtn">insert</button>

    JSONWCFService.svc.cs

    public void Insert(int name, int address)
            {
                string connectionString = System.Configuration.ConfigurationManager.
    ConnectionStrings["Database1ConnectionString1"].ConnectionString;
                SqlConnection con = new SqlConnection(connectionString);
    
                string sql = "INSERT INTO Table1(Name, Address) VALUES (@Name, @Address)";
    
                SqlCommand cmd = new SqlCommand(sql, con);
                cmd.Parameters.AddWithValue("@Name", name);
                cmd.Parameters.AddWithValue("@Address", address);
                try
                {
                    con.Open();
                    int numAff = cmd.ExecuteNonQuery();
    
                }
                catch (SqlException exc)
                {
                }
                finally
                {
                    con.Close();
                }
            }

    IAddService.cs

    public interface IAddService
        {
            [OperationContract]
            [WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
            void Insert(string name, string address);
                
        }

    default.js 

    function insertButtonClick() {
    
            var baseURI2 = "http://localhost:45573/AddService.svc/Insert";
            var name = document.getElementById('txtName').value;
            var address = document.getElementById('txtAddress').value;
    
    WinJS.xhr({
                type: "POST",
                url: baseURI2,
                headers: { "Content-type": "application/json" },
                data: JSON.stringify(txtName+ txtAddress)
            }).then(function complete(request) {
                var resdata = request.responseText;
            }, function error(er) {
                var err = er.statusText;
            })
        }

    Please help  to correct my code or share me some sample code (WinJS.xhr and JSONWCFService).

    Thank you very much!




    Saturday, August 10, 2013 4:46 AM