C# PartialView表单验证,然后在MVC3中调用控制器方法
我是MVC3的新手,在处理事情时遇到了一些问题。现在我有一个局部视图,我已将其简化如下:C# PartialView表单验证,然后在MVC3中调用控制器方法,c#,asp.net-mvc-3,forms,validation,C#,Asp.net Mvc 3,Forms,Validation,我是MVC3的新手,在处理事情时遇到了一些问题。现在我有一个局部视图,我已将其简化如下: @model blah.blah.blah.blah.ForumPost @using (Html.BeginForm()) { <fieldset> <legend>ForumPost</legend> <div class="editor-label"> @Html.LabelFor(model => model
@model blah.blah.blah.blah.ForumPost
@using (Html.BeginForm()) {
<fieldset>
<legend>ForumPost</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ForumID)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ForumID)
@Html.ValidationMessageFor(model => model.ForumID)
</div>
<p>
<input type="submit" value="Create" />
@Html.ValidationSummary(true)
</p>
</fieldset>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
}
有人有什么建议吗?谢谢
如果需要,我可以提供更多代码。Html表单通常提交给控制器操作:
[HttpPost]
public ActionResult Create(ForumPost model)
{
if (!ModelState.IsValid)
{
// validation failed => redisplay the view so that the user can fix the errors
return View(model);
}
// at this stage the model is valid => process it:
service.CreateForumPost(model);
return ...
}
现在,由于这是一个局部视图,您必须小心从该控制器操作以及模型返回的视图。如果不使用AJAX,则应返回整个父视图和父视图模型。如果使用AjaxForm,则只能使用局部模型和视图。同样,在这种情况下,如果成功,您可以向视图返回一个Json结果以指示此成功,以便将要执行的javascript处理程序可以执行相应的操作。中没有“代码隐藏”MVC3@TetsujinnoOni对不起,就像我说的,我是MVC3的新手,我不知道该怎么称呼它。没问题,没必要道歉。这是一种非常不同的方法来控制页面上的怪诞的东西——所谓的生命周期。您的变量命名非常隐晦,其他人很难理解。html表单如何知道调用此方法?在生成表单时,由您指示:
@使用(html.BeginForm(“ActionName”,“ControllerName”)
。如果不这样做(如在代码@中使用(Html.BeginForm())
),则将被调用的控制器操作必须与用于呈现此表单的控制器操作具有相同的名称,但它必须用HttpPost属性修饰。例如,如果您的视图是通过创建控制器操作(/somecontroller/Create
)呈现的,那么如果您在生成表单时未指定操作,则提交时将调用创建后期控制器操作。啊,好的。我理解。显然,在这个项目中,还没有开始任何验证,这就是为什么我完全迷失了方向。对很多事情来说都是杂乱无章的。从现在起,这让我看到了更多,因为我看到了正在通过的具体内容。谢谢
[HttpPost]
public ActionResult Create(ForumPost model)
{
if (!ModelState.IsValid)
{
// validation failed => redisplay the view so that the user can fix the errors
return View(model);
}
// at this stage the model is valid => process it:
service.CreateForumPost(model);
return ...
}