MVC (MVC3) 检查模型是否存在或具有值
我创建了一个工作 DropDownListFor ,它从 Model.IssueSocialSec 选择列表中获取数据,然后将来自数据库的值设置为 Model.SocialDBValue
但是,当我单击编辑链接时,查询存储库将模型传递回页面,这是可行的,但是如果我对页面执行了所需的重定向路由,并且没有任何东西可以绑定模型,那么页面就会失败。我将尝试让它传回一个空模型,但我想我会发布这个,因为我总是喜欢听到有关“最佳实践”和经验教训的反馈。
@Html.DropDownListFor(m => m.SelectedSocial, new SelectList(Model.IssueSocialSec, "Value", "Text", Model.SocialDBValue), "")
I have created a working DropDownListFor which gets the data from a selectlist which is Model.IssueSocialSec and then setting the value coming from the database is Model.SocialDBValue
However, when I click a Edit link which with query a repository passing the Model back to the page, that works, but if I do a needed redirect route to the page and nothing is there to bind the Model, then the page fails. I'm going to try having it pass back an empty Model, but I figured I would post this as I always like to hear feedback on "best practices" and lessons learned.
@Html.DropDownListFor(m => m.SelectedSocial, new SelectList(Model.IssueSocialSec, "Value", "Text", Model.SocialDBValue), "")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您只需将
DropDownListFor
包装在一般来说,我构建 MVC 控制器和操作,以便
Index
将呈现所有配置文件。对于每个配置文件,将呈现一个,其中包含指向“编辑”的 URL,并且该 URL 将包含要编辑的配置文件的
id
。Edit
视图会将表单发布到Edit
,并且配置文件将根据模型的更改进行更新。我建议查看类似 NerdDinner 或 MVC 音乐商店 了解他们如何构建代码。
It sounds like you just need to wrap the
DropDownListFor
in a<form>
with a url pointing to an action that will allow you to edit. The form can use aGET
request if it's an idempotent operation and you could use JavaScript to submit the form when the value of the<select>
is changed, falling back to rendering a button for submission for when JavaScript is disabled.Generally, I structure MVC controllers and actions as so
Index
will render all the profiles. Against each profile, an<a>
will be rendered with a URL pointing to Edit and the URL will include theid
for the profile to edit.Edit
view will post a form toEdit
and the profile will be updated with changes from the model.I recommend looking at something like NerdDinner or MVC Music store to get an idea of how they structure their code.
我最终像这样修复了它:
在我尝试这样做之前:
返回View()
I ended up fixing it like this:
before I was trying to just do:
return View()