因此,我正在开发Web应用程序,但是遇到了一个新的挑战,我坚持了几个星期。我将提供有关我的应用程序和数据模型的背景信息,以及所需的最终结果。

基本应用信息和问题背景:
我的应用旨在用作景观承包商可以用来帮助管理其业务运营的工具。我的应用程序将提供一个可以创建帐户的地方,然后输入其所有客户信息(“客户”数据模型)以及有关他们为每个客户所做的工作的信息(“工作”数据模型) 。客户与工作之间存在一对多的关系(一个客户可以有很多工作,但给定工作只有一个客户)。

背景:
我有两个简单的数据模型,“客户”和“工作”。我的应用程序是在ASP.net MVC3框架中构建的。使用实体框架支架机制,我为每个数据模型(创建,读取,更新,删除)创建了基本的CRUD视图。在大多数情况下,这是很棒的(我可以轻松创建新的客户和工作,并编辑现有的客户和工作)。

业务问题:
我需要允许在我的应用程序中为新作业批量创建。我希望我的用户(景观承包商)能够输入他们当天完成的所有割草工作。因此,我希望该过程的视图填充一个表格,其中包含所有活动的客户端-每个客户端在行旁边都有一个复选框。然后,我希望用户能够为每个为其做新工作的客户选中复选框(割草),然后提交表格(输入完成的工作),结果是为每个这些客户创建新工作。

技术问题:
我最好的猜测是,我需要在控制器中创建一个自定义ViewModel并将其发送到视图,其中ViewModel是基于当前活动客户端创建的新作业的列表。然后在视图中,复选框可以将Client_ID(客户端的唯一标识符)作为其值(这将是ViewModel的一部分。当用户提交表单时,视图会将ViewModel传递回控制器。可以浏览ViewModel作业列表,并为每个选中了复选框的ViewModel作业创建一个新作业。

所以,我的问题是-如何使用控制器执行以下操作:
1.)根据客户端列表中的数据(“客户端”数据模型)在运行时构建ViewModel作业列表?
2)然后如何将其传递给视图?
3.)一旦返回到控制器,如何遍历列表并相应地修改其他数据模型(创建新的“作业”项目)?

我创建了自定义ViewModel,其中包含来自客户和作业的属性,这些属性构成了新的作业条目(客户端名称,客户端地址,客户端ID,作业说明,工作人员,工作人员人数,工作时间,复选框以指示完成等) )。假设用户有50个客户,他修剪的草坪是活跃的客户。我想用50行构造一个ViewModel(以表示可能修剪草坪的每个客户端)。然后,我想将其发送到视图并显示带有复选框的复选框,该复选框指示是否修剪了草坪。当模型返回视图时,控制器将使用复选框中的选中行,并在该表中创建新的“作业”行。

预先感谢您可以提供的任何帮助,我知道这对您中的许多人来说可能很容易。我是C#和MVC3的新手。

更新:
这是我的代码-

工作模式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace LawnTracker.Models
{
    public class Job
    {
        [Key]
        public int Job_ID { get; set; }
        public int Client_ID { get; set; }
        public int Account_ID { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }
        public string Notes { get; set; }
        public string SvcRoute { get; set; }
        public string Service { get; set; }
        public string Date { get; set; }
        public double SvcPriceOverride { get; set; }
        public float SvcQty { get; set; }
        public string UofM { get; set; }
        public bool Invoiced { get; set; }
        public string Crew { get; set; }
        public int TechCount { get; set; }
        public string TimeStart { get; set; }
        public string TimeFinish { get; set; }
        public double TimeSpent { get; set; }
        public string Image1 { get; set; }
        public string Image2 { get; set; }
        public string Image3 { get; set; }
        public double MulchUsed { get; set; }
        public double FertUsed { get; set; }
        public double HerbUsed { get; set; }
        public string NextDue { get; set; }

    }


}


我的MowingJobViewModel模型-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LawnTracker.Models
{
    public class MowingJobViewModel
    {
        public int Client_ID { get; set; }

        public bool Completed { get; set; }

        public string Name { get; set; }

        public string Street { get; set; }

        public string City { get; set; }

        public double SvcPriceOverride { get; set; }

        public string UofM { get; set; }

        public int SvcQty { get; set; }

        public string Notes { get; set; }

        public string Date { get; set; }

        public string Crew { get; set; }

        public int TechCount { get; set; }

        public string SvcRoute { get; set; }

        public string Schedule { get; set; }
    }
}


还有我的JobController-

 // GET: /Job/CreateMowing

        public ActionResult CreateMowing(string route = "", string sched = "")
        {
            List<SelectListItem> listItems = new List<SelectListItem>();
            listItems.Add(new SelectListItem()
            {
                Value = "Lump Sum",
                Text = "Lump Sum"
            });
            listItems.Add(new SelectListItem()
            {
                Value = "Hours",
                Text = "Hours"
            });


            ViewBag.Units = new SelectList(listItems, "Value", "Text");
            ViewBag.Routes = db.Clients.Select(r => r.SvcRoute).Distinct();
            ViewBag.Sched = db.Clients.Select(r => r.MowSched).Distinct();

            var model = from r in db.Clients
                        orderby r.SvcRoute
                        where (r.Mowing == true) &&
                        (r.Status == "Active") &&
                        (r.SvcRoute == route || (route == "")) &&
                        (r.MowSched == sched || (sched == ""))
                        select r;
            if (model.Count() > 0)
            {
                ViewBag.total = model.Select(r => r.MowPrice).Sum();
            }
            else
            {
                ViewBag.total = 0.00;
            }

           /* Build a list of MowingJobViewModel objects based on the above defined list of clients
            * who are subscribed to mowing and active. This will enable batch entry for new jobs done.
            * This list of MowingJobViewModel objects will be sent to the client after a HTTP GET
            * request for the CreateMowing view.  The user will be able to check boxes associated
            * with each client in the client list.  When the form is submitted, the controller
            * receives the model back with the updated information (completed, notes, etc.) about
            * each job.  Then the controller must update the jobs table, adding the new jobs based on
            * the view model returned from the view / client.
            *
            */

            //Create a new list of MowingJobViewModel objects
             IEnumerable<MowingJobViewModel> mjList = new List<MowingJobViewModel>();

            //iterate through the list of clients built from earlier (in model)...
             foreach (var item in model)
             {
             //create new MowingJobViewModel object MJ and add it to the list
             mjList.Add(new MowingJobViewModel()
             {
               Client_ID = item.Client_ID,
               Completed = false,
               Name = (item.FirstName + " " + item.LastName),
               Street = item.Address1,
               City = item.City,
               SvcPriceOverride = item.MowPrice,
               UofM = "Lump Sum",
               SvcQty = 1,
               Notes = "",
               Date = "",
               Crew = "",
               TechCount = 2,
               SvcRoute = item.SvcRoute,
               Schedule = item.MowSched,
              });

             }

             return View(mjList);

             }

**I don't have my view ("CreateMowing.cshtml") worked out correctly, but here is what I have-**

@model IEnumerable<LawnTracker.Models.MowingJobViewModel>

@{
    ViewBag.Title = "Enter Mowing Jobs";
}

<h2>Enter Mowing Jobs</h2>

<div style="float: left; clear:both; width: 100%;">
    <b>Total Jobs: @Html.Encode(Model.Count())</b><br />
    <b>Total Revenue: $@Html.Encode(ViewBag.total)</b><br /><br />
</div>
<p></p>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

<div style="float: right; clear:both; width: 100%;">
     @using (Html.BeginForm("CreateMowing", "Job", FormMethod.Get))
    {
    <table>
    <tr>
        <th></th>

        <th>
            Route
        </th>

        <th>Schedule</th>
        <th></th>
    </tr>
    <tr>
        <td>
            Show:
        </td>

        <td>
            @Html.DropDownList("route", new SelectList(ViewBag.Routes), "--ALL--")
        </td>

        <td>
            @Html.DropDownList("sched", new SelectList(ViewBag.Sched), "--ALL--")
        </td>
        <td>
            <input type="submit" value="Filter" />
        </td>
    </tr>
</table><br /><br />

    }
</div>

<table>
    <tr>
        <th>
            Completed
        </th>
        <th>
            First Name
        </th>
        <th>
            Last Name
        </th>
        <th>
            Street
        </th>

        <th>
            City
        </th>

        <th>
            Service Route
        </th>
        <th>
            Price
        </th>

        <th>
            Units
        </th>

        <th>
            Qty
        </th>
        <th>
            Notes
        </th>

        <th>
            Schedule
        </th>

    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            <input type="checkbox" name="invoiced" value="@item.Client_ID" >
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Address1)
        </td>

        <td>
            @Html.DisplayFor(modelItem => item.City)
        </td>

        <td>
            @Html.DisplayFor(modelItem => item.SvcRoute)
        </td>

        <td>
            @Html.DisplayFor(modelItem => item.MowPrice)
        </td>

        <td>

        </td>

        <td>

        </td>
        <td>

        </td>

        <td>
            @Html.DisplayFor(modelItem => item.MowSched)
        </td>

     </tr>
}

</table>


<div>
    <br />
    @Html.ActionLink("Back to List", "Index")
</div>

最佳答案

您已经创建了一个视图模型,其中包含创建作业时特定客户端的显示属性/数据输入字段。由于您没有给它起一个名字,因此我将其命名为NewJobEntry。如您所料,您现在需要一个视图模型,该模型具有类型List<NewJobEntry>的属性,以表示可以立即创建的可变数量的新作业。

您的控制器将填充列表,并为每个客户端添加一个NewJobEntry实例。

当提供包含列表的模型时,您的视图可以枚举列表并为每个NewJobEntry生成一行。

将数据重新发布到控制器后,默认的ASP.NET MVC绑定程序就可以处理列表,但有一些怪癖。只要字段名称具有顺序索引,默认联编程序就会自动对列表中的对象进行合并。为了确保正确生成这些索引,您将需要在视图中使用具有顺序索引的lambda表达式进行绑定:

Html.CheckboxFor(model => model.JobList[i].IsSelected)

枚举列表时,您可以考虑使用for循环而不是foreach循环。

您还必须注意复选框,因为未选中的复选框实际上不会出现在发送给控制器的发布数据中。这将中断绑定,因为在发布数据中发送的索引可能不再是顺序的(在未选中的复选框处会有空白)。因此,我建议您为客户端ID包括一个隐藏字段。这样,发布数据将始终包含至少一个字段,并且每个列表条目都具有适当的顺序索引。

Html.HiddenFor(model => model.JobList[i].ClientId)

现在,您的帖子数据将类似于以下内容:

JobList_0_IsSelected=true
JobList_0_ClientId=12345
JobList_1_ClientId=12346
JobList_2_IsSelected=true
JobList_2_ClientId=12347


默认的活页夹将处理此问题并重建您的列表。请注意,如果没有客户端ID的隐藏字段,则索引1将丢失,并且默认活页夹将无法正确重建列表。

希望有帮助!

关于c# - 如何在运行时根据现有数据模型中的数据构建自定义动态ViewModel?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13373052/

10-11 02:56
查看更多