- 建立ViewModal
先建立viewmodal :
namespace MyModel.Models { using System; using System.ComponentModel; public class MyJsonViewModel { [DisplayName("代號")] public string UserNo { get; set; } [DisplayName("姓名")] public string UserName{ get; set; } [DisplayName("e-mail")] public string UserMail { get; set; } } }
從database中取出所需欄位,丟給Controller,習慣將撈資料放另一支程式 MyService.cs :
public MyJsonViewModel GetPersonalInfo(string UserNo) { MyJsonViewModel result = new MyJsonViewModel(); string SqlStr = @"SELECT UserNo , UserName , UserMail FROM MyTable WHERE UserNo = @UserNo "; using (DbCommand cmd = Db.GetSqlStringCommand(SqlStr)) { Db.AddInParameter(cmd, "UserNo", DbType.AnsiString, UserNo); using (IDataReader dr = Db.ExecuteReader(cmd)) { if (dr.Read()) { result.UserNo = dr["UserNo"].ToString(); result.UserName = dr["UserName"].ToString(); result.UserMail = dr["UserMail"].ToString(); } } } return result; }
此次用在 Controller 傳給前端的 PartialView 使用 :
public PartialViewResult GetPersonalInfo(string UserNo) { MyService myService = new MyService(); MyJsonViewModel myPartialView = myService.GetPersonalInfo(UserNo); return PartialView("_PersonalView", myPartialView); }
- 使用JObject
待補