问题
I'm using asp.net mvc with aspx view engine to read from an excel file, extract contact information from that, display it to the user and when he\she confirms it would save them in database.
Now in my page I got my DataTable as Model and with a foreach loop I'm showing that to the user. then I have a submit button that when the user click on it I want my datatable back to the Action in a Controller. but my Datatable is null.
How can I have my datatable back to my controller ?
aspx first line :
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Authenticated.master"
Inherits="System.Web.Mvc.ViewPage<System.Data.DataTable>" %>
Controller Action definition :
public virtual ActionResult SaveExcelContacts(DataTable dt)
回答1:
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>
来源:https://stackoverflow.com/questions/13375370/datatable-model-bind-in-mvc