【发布时间】:2015-03-09 22:59:33
【问题描述】:
我是 MVC 的新手,我正在使用一个简单的 FORM,但是,我有一个问题, 出于某种原因,我想更改控制器操作中的绑定模型和 渲染视图,但这不会发生。
例如:
public class Product{
int id {get; set;}
string description {get; set;}
}
和控制器方法:
[POST]
public ActionResult Edite(Product p){
p.description = "HELLOOOOOO!!!"
return View(P);
}
观点:
@model WebSite.Models.Product
@{
ViewBag.Title = "Modificar (Product)";
}
<h2>Modificar (Product)</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4></h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Guardar" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Volver a la Lista", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
但是在渲染视图中,产品的描述不是“HELLOOOOO!!!!”。
为什么 MVC 使用用户输入的值而不是我想要的新模型来渲染视图?
【问题讨论】:
-
您必须向我们展示
Edite视图。 -
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
您将模型发布到
Edite()。如果你想返回一个新模型,那么遵循 PRG 模式并重定向到 GET 方法并构建一个新模型。当您发布并返回视图(而不是模型属性)时,MVC 绑定到ModelState值。 -
谢谢约翰,对不起,我是 Stackoverflow 的新手。贴出的代码是一个示例,不是我的真实案例,但是,我将添加视图示例。
-
@StephenMuecke 谢谢你的回答,是的,我在考虑这个选项,但是,在我的真实情况下,我想渲染一个局部视图,你想用 ajax 做到这一点而不重新加载页面,在这种情况下可以使用 PRG 吗?
标签: c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-5