我创建了一个有效的DropDownListFor,它从一个选择列表中获取数据,该数据是Model.IssueSocialSec,然后设置来自数据库的值为Model.SocialDBValue
但是,当我单击一个带有查询的编辑链接时,存储库将模型传递回页面,这是有效的,但是如果我执行了需要的重定向路由到页面,并且没有任何东西可以绑定模型,那么页面失败。我将尝试将它传回一个空模型,但我想我会发布这个,因为我总是希望听到关于“最佳实践”和经验教训的反馈。
@Html.DropDownListFor(m => m.SelectedSocial, new SelectList(Model.IssueSocialSec, "Value", "Text", Model.SocialDBValue), "")
答案 0 :(得分:1)
听起来你只需要将DropDownListFor
包裹在一个<form>
中,其中一个url指向一个允许你编辑的动作。如果表单是幂等操作,则表单可以使用GET
请求,当<select>
的值发生更改时,您可以使用JavaScript提交表单,然后回退到呈现JavaScript时提交的按钮禁用。
通常,我将MVC控制器和操作结构化为
public class ProfilesController : Controller
{
public IProfileRepository Profiles { get; private set; }
public ProfilesController(IProfilesRepository profiles)
{
Profiles = profiles;
}
[HttpGet]
public ActionResult Index()
{
var profiles = Profiles.All();
return View(new ProfilesModel { Profiles = profiles });
}
[HttpGet]
public ActionResult Edit(int id)
{
var profile = Profiles.GetById(id);
return View(new ProfileModel { Profile = profile });
}
[HttpPost]
public ActionResult Edit(ProfileModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var profile = Profiles.GetById(id);
// update the profile
Mapper.Map(model, profile);
if (Profiles.Update(profile))
{
TempData["message"] = "Profile updated successfully";
}
return RedirectToAction("Edit");
}
}
Index
将呈现所有个人资料。对于每个配置文件,将使用指向“编辑”的网址呈现<a>
,并且该网址将包含要编辑的配置文件的id
。 Edit
视图会将表单发布到Edit
,并会根据模型中的更改更新配置文件。
我建议您查看 NerdDinner 或 MVC Music store 等内容,以了解他们如何构建代码。
答案 1 :(得分:0)
我最终解决了这个问题:
ChildInfoModel childviewmodel = new ChildInfoModel();
return View(childviewmodel);
在我尝试做之前:
return View()