如何从ListItem将整数LocationId导入ViewModel?

时间:2018-03-23 15:51:03

标签: asp.net-mvc asp.net-core-mvc viewmodel selectlistitem

在我的form中,我有一个DropDownList,其中我正在填充LocationsDatabase中的数据。当用户选择LocationName时,相应的LocationId应保存到ViewModel中,以便我可以将其传递给POST方法以将数据保存到Database中1}}。但是,我得到LocationId而不是获得相应的0

在搜索原因后,我发现由于ListItem需要value形式的textstring字段,在保存数据的同时,我被迫使用LocationIdstring转换为.ToString()。如何将LocationId存储到ViewModel

代码段:

控制器

public IActionResult Locate(int Id)
{
    InventoryLocationsHistoryViewModel locationsHistoryVM = new InventoryLocationsHistoryViewModel();

    // Populating Locations DropDownList
    var locationsList = new List<InventoryLocations>();
    locationsList = _context.InventoryLocations.ToList();
    var locations = locationsList.OrderBy(l => l.LocationName).Select(us => new SelectListItem { Value = us.LocationId.ToString(), Text = us.LocationName }).ToList();
    ViewBag.Locations = locations;

    return View(locationsHistoryVM);
}

查看

<label asp-for="LocationId" class="fg-labels" for="locationName"></label>
<select asp-for="LocationId" asp-items="ViewBag.Locations" class="chosen disabledropdowncntrl" data-placeholder="Choose a Location" name="locationName" id="dropDownLocationNames">
    <option value=""></option>
</select>

视图模型

public int LocationId { get; set; }
public InventoryLocations Location { get; set; }

怎么办?

1 个答案:

答案 0 :(得分:0)

发布表单时,参数以输入的locationName=5值命名。那么目前发布的是name="locationName" ,因为你在选择中有这个:

name="locationId"

看起来您需要将其更改为

 x = data.frame(a=c(1,2,3,4), b = c("g1","g2","g3","g4"), 
 dummy_1 = c(1,1,1,0), dummy_2 = c(0,0,1,1))

 a  b dummy_1 dummy_2
 1 g1       1       0
 2 g2       1       0
 3 g3       1       1
 4 g4       0       1

匹配视图模型中的参数名称。

并且不用担心字符串vs int,模型绑定应该能够解决它。