如何通过ASP.NET Core中的链接进行POST

时间:2017-09-11 12:35:34

标签: c# asp.net asp.net-core asp.net-core-1.1

我尝试通过链接POST到SetLanguage操作,但不确定如何完成以下代码:

<form id="selectLanguage" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path" method="post" role="form">
    @foreach (var culture in cultures) {
        <div>                
            <a href="?culture=@culture.Name">@culture.Name</a>
        </div>
    }
 </form>

我应该使用form还是有一种直接方法来发送带有culture : 'EN' param的POST,例如?

@Url.Action(action: "SetLanguage", controller:"Home", values: new { culture = culture.Name }, protocol:"POST")是否有效?

我的控制器代码是

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

4 个答案:

答案 0 :(得分:4)

链接是GET请求。您无法通过链接发布;这就是形式的用途。你需要这样的东西:

<form id="selectLanguage" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path" method="post" role="form">
    @foreach (var culture in cultures) {
        <div>                
            <button type="submit" name="culture" value="@culture.Name">
                @culture.Name
            </button>
        </div>
    }
</form>

然后,无论您点击哪个按钮,都会发布其值。如果您希望它看起来像链接,您可以相应地设置按钮的样式。

或者,您可以保留链接,但是您需要使用AJAX在点击时发布。

答案 1 :(得分:3)

我会对链接本身使用操作,我在我的项目中使用这段特殊代码。它就像一个魅力。

<a asp-controller="YourController"
 asp-action="SetLanguage"
 asp-route-culture="@culture.Name"
 asp-route-returnUri="@Context.Request.Path">
</a>

我的控制器代码如下所示:

  public IActionResult SetLanguage(string culture, string returnUri = "")
        {
            SetSettings(newCultureName);
            return Redirect(returnUri);
        }

希望这可以帮助您完成项目!

答案 2 :(得分:1)

您可以使用JQuery:

@foreach (var culture in cultures)
{
    <div>
        <a href="javascript:setLanguage('@culture.Name')">@culture.Name</a>
    </div>
}

<script type="text/javascript">

    function setLanguage(culture)
    { 
        $.post("/home/setlanguage", { culture: culture})
            .done(function (data) {
                location.reload();
            });
    }
</script>

答案 3 :(得分:1)

您可以创建一个TagHelper,该表单以html格式生成表单,并接收要放入的配置作为参数。 TagHelper的示例: TagHelper类:

 [HtmlTargetElement("HyperLink")]
public class HyperLinkTagHelper : TagHelper
{
    #region Proprietes
    public string AspAction { get; set; }
    public string AspController { get; set; }
    public Method Method { get; set; } = Method.Get;
    public string Class { get; set; }
    public string Style { get; set; }

    private IDictionary<string, string> _routeValues;

    [HtmlAttributeName("asp-all-route-data", DictionaryAttributePrefix = "asp-route-")]
    public IDictionary<string, string> RouteValues
    {
        get => _routeValues ??= new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        set => _routeValues = value;
    }
    #endregion


    #region Injectable

    private readonly IUrlHelper _urlHelper;
    #endregion

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="urlHelper"></param>
    public HyperLinkTagHelper(IUrlHelper urlHelper)
    {
        _urlHelper = urlHelper;
    }

    /// <summary>
    /// Render output 
    /// </summary>
    /// <param name="context"></param>
    /// <param name="output"></param>
    /// <returns></returns>
    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        output.TagMode = TagMode.StartTagAndEndTag;
        var linkName = (await output.GetChildContentAsync()).GetContent();
        var builder = new StringBuilder();
        var method = Method.ToString().ToLower();
        var link = _urlHelper.Action(AspAction, AspController);
        builder.AppendFormat("<form method='{0}' role='form' action='{1}'>", method, link);
        foreach (var (key, value) in _routeValues)
        {
            builder.AppendFormat("<input type='hidden' name='{0}' value='{1}'>", key, value);
        }
        builder.AppendFormat("<input type='submit' value='{0}' class='{1}' style='{2}'/>", linkName, Class, Style);
        builder.Append("</form>");
        output.Content.SetHtmlContent(builder.ToString());
    }
}

用法:

<HyperLink asp-action="SendData" asp-controller="Default" method="Post" asp-route-data="test">Send data</HyperLink>

控制器:

public class DefaultController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult SendData(string data)
    {
        Console.WriteLine(data);
        return RedirectToAction("Index");
    }
}

方法:

public enum Method
{
    Get,
    Post,
    Delete,
    Put
}

注册:

@addTagHelper HyperLinkTagHelper.TagHelpers.HyperLinkTagHelper, HyperLinkTagHelper

Example on Github

我没有使用它,我只是带着意见而来

您可以继承AnchorTagHelper并重写Process方法