DataTable Model Bind in Mvc

扶醉桌前 提交于 2019-12-06 07:19:00

I do not think you will be able to bind to DataTable on submit or at least it is not very good conception. Take a look at the documentation of DataTable http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx. It is too complicated to send all data to client and retrieve it back on the server to reconstruct DataTable object.
You would better extract data from DataTable to your own model class and then try to bind to it on submit. Do not forget to include hidden inputs in the form of your view, so the data will be posted to server and could be bound.

Update - just added some code snippets that could help you solve the problem

// 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");
    }
}

View

<%@ 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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!