所以我有我的模型,我想从下拉列表中选择的现有植物创建一个新植物,该植物具有与旧植物相同的属性,除了科学名称。我创建了一个函数,它将采用新植物名称和旧工厂并创建一个具有旧属性的新工厂。我想知道我应该在我的 Controller 中做什么并查看才能从现有工厂创建这个新工厂。
这是我的模型
public class ExistingPlant
{
public string selectedPlant { get; set; }
public Dictionary<Guid,string> plantList { get; set; }
}
这是我的 Controller 代码
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);
}
和我的 View 代码:
@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")
)
最佳答案
您需要在 View 模型中为新名称设置一个属性,当您提交表单时,获取选定的植物,克隆它,根据 View 模型更新学名并保存。
将您的 View 模型更改为
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; }
}
和 View
@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" />
}
和 Controller 方法
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");
}
关于asp.net-mvc - 从现有 MVC 创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34731050/