2016-09-29 108 views
0

我從ASP.NET core samples複製的語言選擇並添加SetLanguage方法我ASP-動作不呼叫控制器

[HttpPost] 
    public IActionResult SetLanguage(string culture, string returnUrl) 
    { 
     Response.Cookies.Append(
      CookieRequestCultureProvider.DefaultCookieName, 
      CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)), 
      new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) } 
     ); 

     return LocalRedirect(returnUrl); 
    } 

但是控制器,不會被調用的是沒有網絡請求或當我改變JavaScript錯誤語言選擇。任何關於缺少什麼的建議。

@using Microsoft.AspNetCore.Builder 
@using Microsoft.AspNetCore.Http.Features 
@using Microsoft.AspNetCore.Localization 
@using Microsoft.AspNetCore.Mvc.Localization 
@using Microsoft.Extensions.Options 

@inject IViewLocalizer Localizer 
@inject IOptions<RequestLocalizationOptions> LocOptions 

@{ 
    var requestCulture = Context.Features.Get<IRequestCultureFeature>(); 
    var cultureItems = LocOptions.Value.SupportedUICultures 
     .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName }) 
     .ToList(); 
} 

<div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name"> 
    <form id="selectLanguage" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path" method="post" class="form-horizontal" role="form"> 
    @Localizer["Language:"] <select name="culture" asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems">  </select> 
    </form> 
</div> 

呈現的HTML如下:

<div title="Request culture provider: AcceptLanguageHeaderRequestCultureProvider"> 
<form id="selectLanguage" method="post" class="form-horizontal" role="form" action="/Home/SetLanguage?returnUrl=%2F"> 
    Language: <select name="culture" id="requestCulture_RequestCulture_UICulture_Name"><option selected="selected" value="en-GB">English (United Kingdom)</option> 
<option value="en-US">English (United States)</option> 
<option value="en">English</option> 
<option value="de">Deutsch</option> 
<option value="fr">français</option> 
</select> 
    <input name="__RequestVerificationToken" type="hidden" value="CfDJ8GV_4Y4TrKRMt52xrAg49HFabVGQ6RTHVo2cPjiA2tk3yAtt7EFi-dr3P6wRdR6vj0FqDcXgKwvYef8HrVWa9tFupW9eTJMOBQ848jT_zG2t2-0_XNuAFmnOYfAu3DNBuS6DpF8RF8TfmRdTktOQYzk"></form> 
</div> 
+0

如果您使用Postman或任何其他REST API測試工具調用SetLanguage方法,它會工作嗎? – Ignas

回答

0

你添加的JavaScript,使選擇自動後?

(function() { 
$("#selectLanguage select").change(function() { 
    $(this).parent().submit(); 
    }); 
}()); 
+0

我沒有添加這個,因爲我期望ASP.NET自動生成這樣的代碼。添加它並沒有幫助 – Mark

+0

當你添加這個代碼改變'select'時會發生什麼?如果你添加一個提交按鈕,它工作嗎?不,它不會自動提交一個選擇給你,而你沒有告訴它這樣做。 –

+0

你有沒有jquery的頁面,這段代碼依賴於jquery。此代碼來自您試圖模仿https://github.com/aspnet/Entropy/blob/dev/samples/Localization.StarterWeb/wwwroot/js/site.js –