MVC 4 Razor,带有部分视图的过帐表单 [英] MVC 4 Razor, Posting form with partial views
问题描述
我是MVC 4和剃须刀的新手.我有一个包含多个局部视图的视图.由于局部视图的功能,我正计划在其他视图中重用这些视图.
I am new to MVC 4 and razor. I have a view which contains multiple partial views. Due to the functionality of the partial views I am planning to reuse these in other views also.
我的模型是复杂对象的集合,例如:
My model is a collection of complex objects e.g:
public class EmployeeInfo
{
public EmployeeContactInfo contactInfo { get; set; }
public List<TelephoneInfo> phoneDetails { get; set; }
public AddressDetails addressDetails { get; set; }
}
主视图的模型为EmployeeInfo
,其他部分视图的模型分别为TelephoneInfo
,EmployeeContactInfo
和AddressDetails
.
The model of my main view is EmployeeInfo
and other partial views have models as TelephoneInfo
, EmployeeContactInfo
and AddressDetails
respectively.
我尝试使用RenderPartial
,RenderAction
和Partial
加载我的部分视图,例如:
I tried using RenderPartial
, RenderAction
and Partial
to load my partial views e.g:
@using (Html.BeginForm())
{
@Html.Partial("ContactInfo",Model.contactInfo)
}
提交主表单时,主模型没有局部视图的更新值.
When the main form is submitted the main model doesnt have the updated values of the partial views.
我进行了搜索,发现了以下2种建议的解决方案:
I searched for this and found below 2 proposed solutions:
-
使用
EditorFor
-它可以工作并且模型得到更新,但是我不仅收集了文本框,而且还收集了一些具有一些内部操作(如搜索地址)的其他控件,我还需要重用相同的局部视图在其他地方(例如经典ASP.NET中的用户控件)
Use
EditorFor
- It works and the model gets updated but I have collection of not only textbox but other controls which have some internal operations (like searching addresses) too and I also need to reuse the same partial view in other places (like a user control in classic ASP.NET)
使用RenderAction
代替RenderPartial
-这对我不起作用.
Use RenderAction
instead of RenderPartial
- It didn't work for me.
如果我做错了或理解不正确,请告诉我.
Please let me know if I am going wrong or understood anything incorrectly.
推荐答案
另一种选择是创建一个编辑器模板.例如,在您的主视图中:
Another choice is to create an editor template. For example, in your main view:
@using (Html.BeginForm())
{
@(Html.EditorFor(m => m.ContactInfo))
}
现在,在您的Views/Shared文件夹(或Views/ControllerName文件夹,例如Views/Home)中,创建一个名为"EditorTemplates"的新文件夹.在该新文件夹中,创建一个名为EmployeeContactInfo.cshtml
的cshtml视图文件(提示,该cshtml的名称应为数据类型名称,例如string
,bool
,或者在这种情况下为您的客户联系信息类型).在该视图文件中,输入以下内容:
Now, in your Views/Shared folder (or the Views/ControllerName folder eg Views/Home), create a new folder named "EditorTemplates". In that new folder create a cshtml view file named EmployeeContactInfo.cshtml
(tip, the name of the cshtml should be the data type name e.g. string
, bool
or in this case your customer contact info type). In that view file, put something like:
@model EmployeeContactInfo
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email)
当您发回控制器时,这些值将作为您返回的模型的一部分包括在内.
When you post back to the controller, the values will be included as part of the returned model for you.
这篇关于MVC 4 Razor,带有部分视图的过帐表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!