I want to pass the Html.Textbox value to a controller from anchor tag, so that I can search the value passed to a controller. Please tell me how can I achieve this.
<a href="@Url.Action(" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener"Index", "Home", new { })">@p</a>
public ActionResult Index(string String)
{
}
@Html.TextBox("String")
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
use jquery
@Html.TextBox("String", null, new { @class="txtString" })
<a href="@Url.Action(" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener"Index", "Home", new { })" class="linkAction">@p</a>
then in your script
$('.txtString').on('blur', function(){
$('.linkAction').attr('src', '@Url.Action("Index", "Home", new { text = "----" })'.replace("----", $('.txtString').val()));
});
Method 2
You don’t have to use jQuery. If you’re doing a HttpPost, you just need the “name” of the textbox.
On your page:
@using (Html.BeginForm("Index", FormMethod.Post)) {
@Html.TextBox(string.Empty, new { name = "textbox" })
<input type="submit">Submit</input>
}
Then in your controller:
[HttpPost]
public ActionResult Index(string textbox) {
// The name of the string parameter must match the name given to the TextBox element on the page.
}
Method 3
@using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new {@id = "my-form"}))
{
@Html.TextBox("String")
}
<a href="javascript:document.getElementById('my-form').submit();>@p</a>
You can use FormMethod.Post or FormMethod.Get. The latter will append ?String= to the url.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0