如何使用mvc2中的TrypUpdateModel更新ViewData

时间:2011-06-23 11:50:04

标签: asp.net-mvc asp.net-mvc-2 viewdata

我的视图填充了模型属性,一些下拉列表是硬编码的,并通过viewdata传递给视图,问题是Trupdatemodel只更新模型值,我无法更新viewdata值,下面是更新的代码模型但不是viedata下拉列表:

查看:

<div class="editor-field">
                    <% if (ViewBag.mode != "edit")
                       { %>
                    <%: Html.TextBoxFor(model => model.Date)%>
                    <%}else{%>
                        <%: Html.TextBoxFor(model => model.Date, new { @Value = Model.Date.ToShortDateString() })%>
                    <%} %>
                    <%: Html.ValidationMessageFor(model => model.Date) %>
                </div></td></tr><tr><td>Experience level</td><td><div class="editor-field">
                    <%: Html.DropDownListFor(model => model.ExperienceLevelID, (SelectList)ViewData["Experience"], "--select--")%>
                    <%: Html.ValidationMessageFor(model => model.ExperienceLevelID) %>
                </div></td></tr>

                 <tr><td>No of Attendees</td><td><div class="editor-field">

              <%-- <%: Html.DropDownList("attendees1", (SelectList)ViewData["attendees1"], "--select--")%>--%>
               <% if (ViewBag.mode != "edit")
                  { %>

                <%: Html.DropDownList("attendees1", ViewData["attendees1"] as SelectList, "--select--")%>
               <%}else{%>
               <%: Html.DropDownList("attendees1")%>
               <%} %>
                &nbsp;&nbsp; <label>£</label>&nbsp;<%: Html.TextBox("attendeeCost", ViewData["txtAttendees"], new { maxlength = "5", style = "width:40px;" })%> <label>Price/Unit</label>
                </div></td></tr>

                <tr><td>Second Driver</td><td> <div class="editor-field">

                    <label>£</label>&nbsp;<%: Html.TextBoxFor(model => model.SecondDriverPrice, new { maxlength = "5", style = "width:40px;" })%> <label>Price</label>
                    &nbsp;&nbsp; <%: Html.CheckBoxFor(model => model.SecondDriver) %><label>Free</label>
              </div></td></tr>

                <tr><td>No of Helmets</td><td><div class="editor-field">
               <% if (ViewBag.mode != "edit")
                  { %>
               <%: Html.DropDownList("helmets", ViewData["size"] as SelectList, "--select--")%>
               <%}else{%>
                <%: Html.DropDownList("helmets", "--select--")%>
               <%} %>
                &nbsp;&nbsp; <label>£</label>&nbsp;<%: Html.TextBox("unitCosthelmet", ViewData["txtHelmet"], new { maxlength = "5", style = "width:40px;" })%> <label>Price/Unit</label>
                </div></td></tr>

控制器:

 [HttpPost]
    public ActionResult Edit(int id, FormCollection collection)
    {


        ViewBag.mode = "edit";

        // for dropdown track
        ITrackRepository trackResp = new TrackRepository();
        IQueryable<Object> tracks = trackResp.GetVenuesSelectlist();
        ViewData["Venue"] = new SelectList(tracks, "VenueID", "Name");

        // for dropdown for event type
        ITrackdayRepository trackdayResp = new TrackdayRepository();
        IQueryable<EventType> eventTypes = trackdayResp.GetAllEventTypes();
        ViewData["EventTypes"] = new SelectList(eventTypes, "ID", "Name");

        // for dropdown experience
        IExperienceLevelRepository expLevelResp = new ExperienceLevelRepository();
        IQueryable<ExperienceLevel> expLevel = expLevelResp.GetAllExperienceLevels().OrderBy(ExperienceLevel => ExperienceLevel.Name);
        ViewData["Experience"] = new SelectList(expLevel, "ID", "Name");

        // dropdown for helmets
        IProductRepository helmetResp = new ProductRepository();
        Product productHelmet = helmetResp.GetProd(id);

        var attendeesList = Enumerable.Range(1, 80).Select(x => new SelectListItem { Value = x.ToString(), Text = x.ToString() });
        ViewData["attendees1"] = new SelectList(attendeesList.ToList(), "Value", "Text");


        // dropdown for helmets 
        var helmetsList = Enumerable.Range(1, 200).Select(x => new SelectListItem { Value = x.ToString(), Text = x.ToString() });
        ViewData["helmets"] = new SelectList(helmetsList.ToList(), "Value", "Text");

        //ViewBag.helmet = new SelectList(helmets.ToList(), "Value", "Text", product.QtyAvailable);

        // dropdown for garages
        var garagesList = Enumerable.Range(1, 50).Select(x => new SelectListItem { Value = x.ToString(), Text = x.ToString() });
        ViewData["garages"] = new SelectList(garagesList.ToList(), "Value", "Text");

        Event trackday = trackdayResp.GetEvent(id);

        TryUpdateModel(trackday, collection);


        if (ModelState.IsValid)
        {
           // product.DateModified = DateTime.Now;
            trackday.DateModified = DateTime.Now;
            TempData["msg"] = trackdayResp.Save().ToString();
            helmetResp.Save();
            return RedirectToAction("Index");
        }
        else
        {
            return View("Create");
        }


    }

1 个答案:

答案 0 :(得分:1)

您需要在TryUpdateModel的模型中更新要更新的数据才能更新这些值。如果您只是将它们放在ViewData中,数据将只传递给视图,控制器无法使用TryUpdateModel更新这些值。

您需要将当前在ViewData中的选择列表数据包含到Event对象中,或者创建一个包含要更新的值的对象。然后使用TryUpdateModel将使用发布的值更新该数据。当您创建此新对象或将其添加到Event时,请强烈键入此对象的视图,这样您就不需要在视图中执行ViewData强制转换。