如何在Razor视图中选择SelectListItem

时间:2018-02-11 20:42:20

标签: asp.net-mvc razor

我有一个我想编辑的模型(位置)。这个模型有一个名为 ActivityId 的字段。我通过ViewData发送一个ActivityId-s数组视图并将它们转换为SelectList。 我希望使用下拉列表中的所选项目(字符串)设置位置的ActivityId字段(长) - 我需要在进入控制器的Post Action之前以某种方式从字符串到很长时间完成转换(的 EditConfirmed

型号:

 [Table("location")]
 public partial class Location
    {
        public Location()
        {
            StoryLocation = new HashSet<StoryLocation>();
            UserStoryLocation = new HashSet<UserStoryLocation>();
        }

        [Column("id", TypeName = "bigint(20)")]
        public long Id { get; set; }
        [Column("description")]
        [StringLength(255)]
        public string Description { get; set; }
        [Column("name")]
        [StringLength(255)]
        public string Name { get; set; }


        [Column("activity_id", TypeName = "bigint(20)")]
        public long? ActivityId { get; set; }
        [ForeignKey("ActivityId")]
        [InverseProperty("Location")]
        public Activity Activity { get; set; }
       }
    }




 [Table("activity")]
    public partial class Activity
    {
        public Activity()
        {
            Location = new HashSet<Location>();
        }

        [Column("activity_id", TypeName = "bigint(20)")]
        public long ActivityId { get; set; }
        [Column("description")]
        [StringLength(255)]
        public string Description { get; set; }
        [Column("name")]
        [StringLength(255)]
        public string Name { get; set; }
        [Column("type")]
        [StringLength(255)]
        public string Type { get; set; }

        [InverseProperty("Activity")]
        public ICollection<Location> Location { get; set; }
    }

控制器:

    [HttpGet]
            public IActionResult Edit(long id = 0)
            {

                Location loc = this.context.Locations.Find(id);


                if (loc == null)
                {
                    return NotFound();
                }
                ViewData[Constants.ViewData.TActivities]=this.context.Activities
                                .Select(elem=>
                                       new SelectListItem
                                          {
                                          Text=elem.Name,
                                          Value=elem.ActivityId.ToString()
                                          }
                                       ).ToList();
                return View(loc);
            }

查看

@using AdminMVC.Models
@using AdminMVC.ConfigConstants
@using Newtonsoft.Json
@model AdminMVC.Models.Location

@{
    List<SelectListItem> dropActivities=ViewData[Constants.ViewData.TActivities] as List<SelectListItem>;
}

<html>
    <head>
    </head>
    <body>
        <div id="form">

        </div>
        <div id="page">
        @using (Html.BeginForm("Edit","Location",FormMethod.Post))
        {
            <div id="table">
            <label>Set Location:</label>
            <table border="">

               @Html.DisplayFor(x=>x.Id)
            <tr>
                <td>@Html.DisplayNameFor(x=>x.Name)</td>
                <td>@Html.EditorFor(x=>x.Name)</td>
            </tr>
            <tr>
                <td>@Html.DisplayNameFor(x=>x.Description)</td>
                <td>@Html.EditorFor(x=>x.Description)</td>
            </tr>

            <div>
            <label >Select Activity:</label>
             @Html.DropDownList("Activity",dropActivities) //i need to somehow convert the selected value from the dropdown to long before the form is sent to the controller
            </div>
             </table>
             </div>
             <div id="control-panel">
            <input type="submit" value="Edit">
            </div>
        }
    </body>
    </div>
</html>

发布到控制器

[HttpPost, ActionName("Edit")]
            public IActionResult EditConfirmed(Location editLoc) 

            {
                if (ModelState.IsValid)
                {
                    this.context.Entry(editLoc).State = EntityState.Modified;
                    this.context.SaveChanges();
                    return RedirectToAction("Index");
                }
                return View(editLoc);
            }

P.S :到目前为止,发送到Post Action的Location的ActivityId为null。我需要它很长。

1 个答案:

答案 0 :(得分:0)

我使用ViewData组件解决了这个问题。我首先使用NewtonSoft序列化SelectList,然后将其添加到ViewData字典中。渲染视图时,我将使用DropDownList razor Html Helper方法。

<强>模型

public class FixedLocation
{
    [Column("id", TypeName = "bigint(20)")]
    public long Id { get; set; }
    [Column("coords")]
    [StringLength(255)]
    public string Coords { get; set; }
    [Column("name")]
    [StringLength(255)]
    [Required]
    public string Name { get; set; }
    [Column("google_id")]
    [StringLength(255)]
    [Required]
    public string GoogleId { get; set; }
}

获取SelectListItem列表的扩展方法

public static IEnumerable<SelectListItem>  ToSelectList<T,Tkey,Tvalue>(
                                         this IQueryable<T> myenum,
                                         Func<T,(Tkey,Tvalue)>kvpair)
                 {
                   return myenum.Select(elem=>kvpair(elem))
                                .Select(tuple=>new SelectListItem{                                                                          
                                                 Text=tuple.Item1.ToString(),                                                  
                                                 Value=tuple.Item2.ToString()
                                                                });
                 }

<强>控制器:

public IActionResult Create()
        {
            Location targetLocation = new Location();                
            ViewData[Constants.ViewData.TFixedLocations]=
                                this.context.FixedLocation
                                .ToSelectList<FixedLocation,string,long>
                                 (elem=>(elem.Name,elem.Id)).ToList();

            return View(targetLocation);
        }

查看:

    @using AdminMVC.Models
    @model AdminMVC.Models.Location
    @using AdminMVC.ConfigConstants

    @{
      dropFixedLocations=ViewData[Constants.ViewData.TFixedLocations] as List<SelectListItem>;
    }
                <div>
                <label >Select FixedLocation:</label>
                 @Html.DropDownListFor(x=>Model.Id,dropFixedLocations)
                </div>