所以我有我的模型,我想从现有工厂创建一个新工厂,该工厂选自下拉列表,其属性与旧工厂相同,但科学名称除外。我创建了一个将采用新工厂名称的函数和旧工厂一起创造了一个具有旧属性的新工厂。我想知道我应该在我的控制器和视图中做什么,以便从现有工厂创建这个新工厂。
这是我的模特
public class ExistingPlant
{
public string selectedPlant { get; set; }
public Dictionary<Guid,string> plantList { get; set; }
}
这是我的控制器代码
public ActionResult CreateFrom()
{
ExistingPlant existing = new ExistingPlant();
Dictionary<Guid, string> plants = new Dictionary<Guid, string>();
foreach(var item in context.Plants){
plants.Add(item.PlantId , item.ScientificName);
}
existing.plantList = plants;
existing.selectedPlant = "Value";
var plant = context.Plants.Where(d => d.ScientificName == existing.selectedPlant);
string temp = existing.selectedPlant;
Plant p = (Plant) plant;
CopyExisting(p,temp);
return View(existing);
}
和我的观看代码:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset id="field">
<div>
<label> Scientific Name:</label>
</div>
<div class="editor-field">
@Html.EditorFor(m => m.selectedPlant)
@Html.ValidationMessageFor(m =>m.selectedPlant)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
@Html.DropDownListFor(
m => m.selectedPlant,
new SelectList(Model.plantList, "Key", "Value")
)
}
答案 0 :(得分:2)
您需要在视图模型中为新名称提供属性,并在提交表单时,获取所选工厂,克隆它,根据视图模型更新科学名称并保存。
将您的视图模型更改为
public class CopyPlantVM
{
[Display(Name = "Existing Plant")]
[Required(ErrorMessage = "Please select an existing plant")]
public Guid ExistingPlant { get; set; }
public SelectList ExistingPlantList { get; set; }
[Display(Name = "New scientific name")]
[Required(ErrorMessage = "Please enter new scientific name")]
public string Name { get; set; }
}
以及
的观点@model CopyPlantVM
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.ExistingPlant)
@Html.DropDownListFor(m => m.ExistingPlant, Model.ExistingPlantList, "Please select")
@Html.ValidationMessageFor(m => m.ExistingPlant)
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name)
<input type="submit" value="Create" />
}
和控制器方法
public ActionResult CreateFrom()
{
CopyPlantVM model = new CopyPlantVM();
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult CreateFrom(CopyPlantVM model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// Get the selected plant
Plant existingPlant = db.Plants.Where(p => p.PlantID = model.ExistingPlant).FirstOrDefault();
// Create a new plant based on existing plant but with new name
Plant newPlant = new Plant
{
ScientificName = model.Name,
// set other properties based on existing plant
};
db.Plants.Add(newPlant);
db.SaveChanges();
return RedirectToAction(...);
}
private void ConfigureViewModel(CopyPlantVM model)
{
model.ExistingPlantList = new SelectList(db.Plants, "PlantId", "ScientificName");
}