How do I create multiple entries in one view in C# ASP.NET MVC?

可紊 提交于 2019-12-11 08:32:48

问题


I have a Company model and an Employee model and I want to create a Company and then create multiple employees for the company in one view.

How should I do this in the view?

And what should I do in the Create POST method to support this multi-entry view?


回答1:


I really have no idea what you are talking about but here's a wild guess: One entry Foo, multiple enries, IEnumerable<Foo>. Sounds familiar?




回答2:


If I understand the question, I think this article is relevant: http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

My suggestion is to try to take advantage of the default model binder's behavior by naming your fields appropriately. Refer to the article for specific naming conventions for various situations.

EDIT: added the example view logic below. Note, calling Html.Hidden and Html.Input with the third parameter as an anonymous type with the id property specified is not really required; that's my preference for ensuring that those functions don't produce HTML elements with invalid id attributes (containing square brackets).

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
        <title>Example</title>
</head>
<body>
        <div><%
// Get your list of data objects from the model somehow.  This will be specific to your model
IEnumerable<MyData> items = Model as IEnumerable<MyData>;

// if there are items
if (items != null)
{
    // then iterate over them to create fields inside of a form
    using (Html.BeginForm())
    {
        int itemIndex = 0;
        foreach (var item in items)
        { %>
            <div>
                <%= Html.Hidden("MyData[" + itemIndex + "].MyDataID", item.MyDataID, new { id = "MyData_" + itemIndex + "_MyDataID" })%>
                <%= Html.TextBox("MyData[" + itemIndex + "].FirstName", item.FirstName, new { id = "MyData_" + itemIndex + "_FirstName" })%>
                <%= Html.TextBox("MyData[" + itemIndex + "].LastName", item.LastName, new { id = "MyData_" + itemIndex + "_LastName" })%>
            </div><%
                             itemIndex++;
        }
    }   
} %>
        </div>
</body>
</html>

You can then have an action method in your controller to handle the posted data:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Example(IList<MyData> MyData)
    {
        // the MyData parameter will automatically be populated by the default ModelBinder using the values stored in the form collection (the posted data).
    }



回答3:


If the default model binder (the object that converts the form values to the object you're using as a parameter in the action method) is not sufficient for your purposes, you might consider using a custom model binder




回答4:


I think I know what you are asking for. You need to pass a company and multiple employees to the view so that they are strongly typed. Let me know if I am wrong.

What I do when I need multiple objects in a view is I create a "ViewModel" class. I usually create domain model stuff in a separate project and then I use the models folder in the MVC project to house my ViewModels.

So create a class like this

public class SampleViewModel
{

     public SampleViewModel() { }

     public Company Company { get; set; }

     public IEnumerable<Employee> Employees { get; set; }

}

Now bind your view to the sample view model.

public ViewResult SampleAction(SampleViewModel svm)
{
     if (svm == null)
          svm = new SampleViewModel() { Company=/*getcompany*/, Employees=/*get ienumerable employees */ };
}

This technique has served my purposes quite well. Hopefully this is what you were looking for.

EDIT: I read one of your comments Fred and I must not have enough rep to reply to other answers or something (sorry, I'm new). To generate these fields on the fly in the view you would obviously bind UI to the company field (Model.Company) first, then enumerate through the IEnumerable (Model.Employees) and creating whatever UI is necessary on each of them. I'm relatively new to ASP.NET MVC so I'm not sure how this affects model binding on POST, but at the very lease I'm sure you could iterate through the post values in your action method and create an IEnumerable list to bind back to your ViewModel.

If the number of fields on the view is dynamic and you get an X number of employees back then you would have to iterate through the post collection to bind them to your ViewModel. From there you can do whatever you need to with the company and the employees, plugging them into your domain model, etc.

If you are loading the form for the first time you are probably not going to have any employees in the list so no UI would load. You would need to check the size of the list, if zero you would generate one set of UI components bound for Employee. You would then probably have javascript button for adding another employee that duplicates this set of UI for as many times as they need to.



来源:https://stackoverflow.com/questions/3198651/how-do-i-create-multiple-entries-in-one-view-in-c-sharp-asp-net-mvc

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