代码之家  ›  专栏  ›  技术社区  ›  user29439

如何使用ASP.NET MVC实现特定于区域性的地址窗体?

  •  1
  • user29439  · 技术社区  · 16 年前

    我们目前有一个带有更新面板的WebForms控件。代码隐藏包含基于所选国家/地区显示/隐藏字段的逻辑。这对于WebForms来说很好,但是我们正在转向MVC,我很难理清这个问题。我还需要将其本地化,既可以本地化资源字符串,也可以显示不同国家/地区的不同表单字段。

    我们当前将资源字符串存储在资源文件夹中的.resx文件中。每个国家的地址字段存储在一个XML文档中,当国家发生变化时,我们将加载和解析该文档。然后用它来定位相应的控件并显示/隐藏必要的控件。最后一点是验证消息。

    2 回复  |  直到 16 年前
        1
  •  2
  •   Ben Scheirman    16 年前

    <%= Html.RenderPartial("_addressForm-" + countryCode) %>
    

    同样,helper方法可能会使这更容易/更透明。

    最后,您使用什么类型的验证?视图模型的内置MVC2验证属性?如果是这样,我相信这是内置于属性中的,您可以使用这些属性来指定必需的字段等。

    希望这有帮助。

        2
  •  0
  •   user29439 user29439    16 年前

    我发现我试图对我的资源类型错误地使用反射,并且能够创建一些方法来获取正确的资源:

    public string GetLabel(string control)
    {
        string strResourceName;
        try
        {
            AddressInfoField field = AddressFields.First(f => f.m_strControl == control);
            strResourceName = field.m_strName;
        }
        catch // Catch everything
        {
            return string.Empty;
        }
    
        if (string.IsNullOrEmpty(strResourceName))
            return string.Empty;
    
        return GetResource(strResourceName);
    }
    
    public string GetValidationMessage(string control)
    {
        string strResourceName;
        try
        {
            AddressInfoField field = AddressFields.First(f => f.m_strControl == control);
            strResourceName = field.m_strName;
        }
        catch // Catch everything
        {
            return Addressing.Required;
        }
    
        if (string.IsNullOrEmpty(strResourceName))
            return Addressing.Required;
    
        return GetResource(strResourceName + "Required");
    }
    
    private static string GetResource(string strResourceName)
    {
        PropertyInfo property = typeof (Addressing).GetProperty(strResourceName, BindingFlags.Public | BindingFlags.Static);
        if (property == null)
            throw new InvalidOperationException("Could not locate a resource for Addressing." + strResourceName);
        if (property.PropertyType != typeof(string))
            throw new InvalidOperationException("The requested resource does not return a string.");
        return (string) property.GetValue(null, null);
    }
    

    <li id="city" if="Model.IsCityVisible">
        <label for="City">${Model.GetLabel("City")}</label>
        ${Html.EditorFor(x => x.City)}
        !{Html.ValidationMessage("City", Model.GetValidationMessage("City"))}
    </li>
    
    推荐文章