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

46qrfjad  于 2023-05-19  发布在  .NET
关注(0)|答案(4)|浏览(158)

我尝试通过链接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'参数的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);
}
qaxu7uf2

qaxu7uf21#

链接是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 来发布点击。

rvpgvaaj

rvpgvaaj2#

我将使用GET方法对链接本身使用操作,而不是依赖于POST方法。我在我的项目中使用了这段特殊的代码,它工作起来很有魅力。

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

z2acfund3#

你可以使用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>
kzipqqlq

kzipqqlq4#

您可以创建一个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方法

相关问题