2012-11-14 72 views
1

我使用asp.net mvc與aspx視圖引擎讀取excel文件,從中提取聯繫人信息,將其顯示給用戶,並且當他確認它將它們保存在數據庫中時。DataTable模型綁定Mvc

現在在我的頁面中,我將我的DataTable作爲模型和foreach循環向用戶顯示。那麼我有一個提交按鈕,當用戶點擊它時,我希望我的數據表可以返回到控制器中的操作。但我的Datatable爲空。

我該如何將我的數據表放回我的控制器?

ASPX第一行:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Authenticated.master" 
Inherits="System.Web.Mvc.ViewPage<System.Data.DataTable>" %> 

控制器動作定義:

public virtual ActionResult SaveExcelContacts(DataTable dt) 
+0

這是一個可怕的想法,以數據表與asp.mvc – NickD

回答

1

我不認爲你將能夠綁定到DataTable上提交,或至少它不是很好的概念。看看DataTablehttp://msdn.microsoft.com/en-us/library/system.data.datatable.aspx的文檔。將所有數據發送到客戶端並將其恢復到服務器上以重建對象是非常複雜的。
您最好將數據從DataTable提取到您自己的模型類,然後嘗試在提交時將其綁定到它。不要忘記以視圖的形式包含隱藏的輸入,因此數據將被髮布到服務器並可能被綁定。

更新 - 只是增加了一些代碼片段,可以幫助你解決問題

// some service for data retrieval 
public interface IUserService{ 
    /// <summary> 
    /// Extracts MyUserInfo object from DataTable (or excel) 
    /// </summary> 
    MyUserInfo GetUserInfo(int id); 
    void SaveUserInfo(MyUserInfo userInfo); 
} 

// model class 
public class MyUserInfo 
{ 
    public int UserId { get; set; } 
    public string Name { get; set; } 
} 

//controller 
public class MyController : Controller 
{ 
    IUserService userService; 

    [HttpGet] 
    public ActionResult UserInfo(int userId) 
    { 
     var user = userService.GetUserInfo(userId); 

     return View(user); 
    } 

    [HttpPost] 
    public ActionResult UserInfo(MyUserInfo myUserInfo) 
    { 
     userService.SaveUserInfo(myUserInfo); 
     return RedirectToAction("SomeOtherAction","OnControllerOfYourChoice"); 
    } 
} 

查看

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyUserInfo>" %> 
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
    <% using (Html.BeginForm("UserInfo","MyController")) 
     { %> 
     <label>UserName:</label> 
     <%= Model.Name %> 
     <%= Html.HiddenFor(m => m.UserId) %> 
     <%= Html.HiddenFor(m => m.Name) %> 
     <input type="submit" name="ConfirmUser" value="Confirm" /> 
    <%} %> 
</asp:Content> 
+0

它結合可以通過強制鍵入數據集。如果您遇到問題,請將數據集綁定到對象,並使用poco通過propertychanged事件填充,或者僅使用setter更新相應的字段。 –