【问题标题】:ASP.NET MVC Multi-language feature does not work as expectedASP.NET MVC 多语言功能无法按预期工作
【发布时间】:2015-09-27 16:23:46
【问题描述】:

我的应用程序使用 单选按钮 例如

@using (Html.BeginForm("SetCulture", "Home"))
{
<input type="radio" name="culture" id="en-us" value="en-us" class="culture" /> English
<input type="radio" name="culture" id="tr" value="tr" class="culture" /> Türk
}

但是当我使用 图像类型的输入时,它不会发送想要的 VALUE

@using (Html.BeginForm("SetCulture", "Home"))
{
<input type="image" src="~/Content/Images/en.png" name="culture" id="en-us" value="en-us" class="culture" /> 
<input type="image" src="~/Content/Images/tr.png" name="culture" id="tr" value="tr" class="culture" />
}

jQuery 代码:

$(".culture").click(function () {
     $(this).parents("form").submit(); // post form
});

HomeController 代码:

public ActionResult SetCulture(string culture){
    // action code here
}

我看不出图像无法正常工作的原因,但由于某种原因它发生了。有什么想法吗?

非常感谢

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    在第一个代码块(使用&lt;input type="radio" .. /&gt;)中,您的表单只会回发一个culture 的值(所选单选按钮的值)。

    在第二个代码块中(使用&lt;input type="image" .. /&gt;),您的表单将回发两个输入的值,因此您的表单数据为culture=en-US&amp;culture=tr

    DefaultModelBinder 将绑定第一个值并忽略第二个值,因此 POST 方法中的culture 的值将始终为“en-US”,无论您单击哪个图像。

    一个选项是禁用另一个输入(例如,禁用的输入不会回发值

    $(".culture").click(function () {
        $(this).siblings().prop('disabled', true); // disable the other input
        $(this).parents("form").submit(); // post form
    });
    

    处理此问题的另一个选项是使用&lt;img&gt; 标记和文化值的隐藏输入

    <input type="hidden" name="culture" id="culture"/>
    <img src="~/Content/Images/en.png" data-culture="en-US" class="culture" />
    <img src="~/Content/Images/tr.png" data-culture="tr" class="culture" />
    
    $('.culture').click(function () {
        $('#culture').val($(this).data('culture')); // update the hidden input
        $('form').submit();
    })
    

    【讨论】:

    • 虽然这很有意义,但修复没有奏效
    • 那么您问题中的代码是您真实视图中的确切代码吗(我所展示的确实有效)?
    • 是的,它也适用于文本(在收音机旁边),但我需要点击标志图像。是否有其他可能满足要求的控件?谢谢
    • 您可能遇到的一个问题是type="image" 将根据浏览器进行提交(即您提交两次)。可以在脚本最后一行添加return false,防止默认提交。
    • 您始终可以考虑将单选按钮设置为图像 - 一些示例 herehere
    猜你喜欢
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    相关资源
    最近更新 更多