ASP.NET MVC 多语言功能未按预期工作

ASP.NET MVC Multi-language feature does not work as expected

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

@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
});

家庭控制器代码:

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

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

非常感谢

在第一个代码块中(使用 <input type="radio" .. />),您的表单只会 post 返回 culture 的一个值(所选单选按钮的值)。

在第二个代码块中(使用 <input type="image" .. />)您的表单将 post 返回两个输入的值,因此您的表单数据是 culture=en-US&culture=tr

DefaultModelBinder 将绑定第一个值并忽略第二个值,因此 POST 方法中 culture 的值将始终为 "en-US",而不管哪个图像你点击。

一个选项是禁用其他输入(禁用的输入不会 post 返回一个值,例如

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

处理此问题的另一种选择是将 <img> 标签与文化值的隐藏输入结合使用

<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();
})