2014年10月22日 星期三

ASP.NET MVC Web API 資料庫處理 using

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Net.Http.Formatting;
using System.Data;
using MvcMusicStore.Models;
using System.Data.Entity;
using System.Configuration;
using System.Data.SqlClient;

namespace MvcMusicStore.Controllers
{
    public class ExtJSApiController : ApiController
    {     
        public dynamic ReviewDataGet(FormDataCollection form)
        {
            string conn = ConfigurationManager.ConnectionStrings["MvcMusicStoreContext"].ConnectionString;
            DataTable dt = new DataTable();
            string strCheck = form.Get("x");
            string strAlbumID = form.Get("AlbumID");
            string strTitle = form.Get("Title");
            using (SqlConnection sqlConnection = new SqlConnection(conn))
            {
                string strSql = "SELECT * FROM Albums WHERE AlbumID LIKE @AlbumID AND Title LIKE @Title";

                SqlCommand sqlCommand = new SqlCommand(strSql, sqlConnection);
                sqlCommand.Parameters.AddWithValue("@AlbumID", "%" + strAlbumID + "%");
                sqlCommand.Parameters.AddWithValue("@Title", "%" + strTitle + "%");
                sqlConnection.Open();
                dt.Load(sqlCommand.ExecuteReader());
            }
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            return new ApiResponse()
            {
                success = true,
                msg = "",
                ds = ds
            };
        }
        public dynamic AlbumComboGet()
        {
            DataTable dt = new DataTable();
            using (SqlConnection sqlConnection = new SqlConnection(conn))
            {
                string strSql = "SELECT AlbumID AS 'TEXT',AlbumID AS 'VALUE' FROM Albums";
                SqlCommand sqlCommand = new SqlCommand(strSql, sqlConnection);
                sqlConnection.Open();
                dt.Load(sqlCommand.ExecuteReader());
            }
            return dt;
        }
    }
    public class ApiResponse
    {
        public DataSet ds { get; set; }
        public string msg { get; set; }
        public bool success { get; set; }
    }
}


沒有留言:

張貼留言