I am trying to use #Html.ActionLink and send the value of my #Html.DropDownList selected item.
here is my code:
<span class="MemberList">
#Html.DropDownList("ParticipantList", new SelectList(ViewBag.ParticipantList, "UserName", "UserName", ViewBag.ParticipantList), new { #class = "members" })
</span>
<span>
#Html.ActionLink("Login", "Impersonate", "Studio", new { username = DropDown.SelectedValue }, new { #class = "gobutton3" })
</span>
So I am wondering how could I send the value to the ActionLink
the only way to add dynamic content to a link is through script
<a class="lnkLogin" href="#">Login</a>
and then in your script
$('.lnkLogin').on('click', function(){
var url = '#Url.Action("Impersonate", "Studio", new { username = "----" })';
url = url.replace("----", $('#ParticipantList').val());
window.location = url;
});
this will redirect using the window.location. being a login you may want to do an ajax call to verify credentials before redirecting.
Related
Newbie to MVC, please excuse me if my question is not clear.
My view - https://abc.somecompany.org/ has the URL (being generated in a home controller )
#Url.Action("Index", "ContName" ,
new { id = viewModel.Id }, Request.Url.Scheme);
When I deploy it to the dev server, instead of showing the URL as
https://abc.somecompany.org/ContName/
or
https://abc.somecompany.org/ContName/Index
It is being changed to https://abc-server-8088/ContName, which obviously does not work outside the organization .
Why is the root URL being changed from abc.somecompany.org/ to abc-server-8088? Similar issue in both dev and test. This is being changed to something else
Do not want to change it to URL Content , because i have action and controller
viewModel.URLLINK = Url.Action(Etion.Index, Entroller.ContName,
new { id = viewModel.Id }, Request.Url.Scheme);
Want the same root URL (~) to show up in the emails
Try this easy solution:
#{
var myLink = $"{Request.Url.Scheme}://{Request.Url.Host}{#Url.Action("actionName", "controllerName", new { id = #Model.id })}";
Link
}
A short Review:
Html.ActionLink generates an tag. Forexample:
#Html.ActionLink("link text", "someaction", "somecontroller", new { id = "123", foo=5 }, new { #class = "btn btn-primary" })
generates:
link text
Url.Action returns only a url. Forexmple, Url.Action("someaction", "somecontroller", new { id = "123" }) generates:
/somecontroller/someaction/123
But, the nice point about Url.action is that you can combine it with anchor tag to create the link content on the fly. For instance:
<a href="#Url.Action("actionName", "controllerName", new { id = #Model.id })">
<img src="#Model.src" />
</a>
I have added the following route before the default route
routes.MapRoute(
name: "RecordDefault",
url: "{controller}/{action}/{name}",
defaults: new { controller = "Person", action = "Record" }
);
I can hit the page I want using: sitename/Person/Record/John
But I have an global search in the navigation with the following code
#using (Html.BeginForm("Record", "Person", FormMethod.Get, new { #class = "navbar-form navbar-left" }))
{
#Html.TextBox("name", "", new { #class = "form-control", placeholder = "Search Name" })
}
When I submit the form the following URL is displayed: sitename/Person/Record?name=John
What do I have to do to ensure the URL is formatted without the query string parameter?
Thanks
Not the same as the posted duplicate, that marked answer does not resolve my problem and according to the comments it also didnt work for others.
Your form generates ../Person/Record?name=John because a browser has no knowledge of your routes (which is c# code running on your server). And the HTML standards require that the value of successful form controls be added as query string values when the method is GET.
In order to generate your preferred url (../Person/Record/John), you need javascript to intercept and cancel the default submit, and build a url to navigate to. Using jQuery:
$('form').submit(function() {
var baseUrl = $(this).attr('action');
// or var baseUrl = '#Url.Action("Record", "Person")';
var url = baseUrl + '/' + $('#name').val();
location.href = url; // redirect
return false; // cancel the default submit
});
Use form post FormMethod.Post instead of Get. So the value will be not appeared in querystring.
#using (Html.BeginForm("Record", "Person", FormMethod.Post, new { #class = "navbar-form navbar-left" }))
{
#Html.TextBox("name", "", new { #class = "form-control", placeholder = "Search Name" })
}
In your Controller add the following -
[HttpPost]
public ActionResult Record(string name)
{
//code for what needs to be performed.
return View();
}
In your view add the following code replacing your existing and check -
#using (Html.BeginForm("Record", "Person", FormMethod.Post))
{
#Html.TextBox("name")
<input type="submit" />
}
Example:
<div id="result"> some action </div>
#Ajax.ActionLink("Vote", "vote", new { id = Model.Catalog_Id, vote = result }, new AjaxOptions { HttpMethod = "POST", OnSuccess = "location = location", Confirm = "Are you sure to vote?" })
Div result will change immediately when user selects a different radio button value. I want to pass latest radio button value to controller to insert data. Is that possible?
Using ajax method call can solve the problem
I am trying to get my product search URL to look like "Products/Search/{search term here}".
I am using attribute based routing and my controller action looks like this:
[HttpGet]
[Route("Products/Search/{searchTerm?}", Name="ProductSearch")]
public ActionResult Search(string searchTerm = "")
{
return View();
}
I have tried using the HTML Helper for BeginForm and BeginRouteForm (shown below) but have not had luck with either. The right action is being called, but my URL looks like "Products/Search?searchTerm"
BeginRouteForm
#using (Html.BeginRouteForm("ProductSearch", new { searchTerm = "" }, FormMethod.Get, new { Class = "navbar-form navbar-right", role = "search" }))
{
<div class="form-group">
#Html.TextBox("searchTerm", null, new { Class = "form-control", placeholder = "Item # or Name" })
</div>
<button type="submit" class="btn btn-default">Search</button>
}
BeginForm
#using (Html.BeginForm("Search", "Products", new { searchTerm = "" }, FormMethod.Get, new { Class = "navbar-form navbar-right", role = "search" }))
{
<div class="form-group">
#Html.TextBox("searchTerm", null, new { Class = "form-control", placeholder = "Item # or Name" })
</div>
<button type="submit" class="btn btn-default">Search</button>
}
I have gone through debugging and the right route is selected, the URL is just not displaying how I wanted it to. What am I missing?
Here is the solution I suggest -
You have the following controller Action -
[HttpGet]
public ActionResult Search(string searchTerm = "")
{
return View();
}
Let the view be -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#click').click(function (e) {
var name = $("#search").val();
var url = '#Url.Action("Search", "Action")' + '/' + name;
window.location.href = url;
});
});
</script>
<input type="text" name="searchText" id="search"/>
<input type="button" value="click" id="click"/>
And when you click the button -
Do not forget to have proper route to be added on to the route configuration -
routes.MapRoute(
name: "searchaction",
url: "{controller}/{action}/{searchTerm}",
defaults: new { controller = "Action", action = "Search" }
);
The problem you think you are experiencing isn't because of anything about ASP.Net MVC. All Html Forms that use the method GET will translate all input elements into QueryString parameters. This is just a W3C standard.
If you want this to work, you'll have to write jQuery to throw an event before the form is submitted, take the text value from the input store it temporarily, empty the input box, and then update the action by appending the temporary value.
I don't think that BeginRouteForm works the way that you're expecting it to. According to the documentation, all that the method does is insert a <form> using the arguments provided. If you had provided something other than an empty string for the route value such as , new { searchTerm = "somesearchterm" }, you would see that show up in the Url as "/product/search/somesearchterm". As it is now, however, the form will be processed as normal, putting the search term on the Url as a normal query parameter.
I have a link that opens a pdf in a new window, without leaving the page. I had this link working...
<script type="text/javascript">
$(function () {
$("#DatePicker").mask("99/99/9999").datepicker({ maxDate: new Date() });
});
if (document.images) {
var pic1 = new Image(100, 200);
pic1.src = '<%=Url.Content("~/images/calendarContent.png") %>'
}
</script>
<%= Html.ActionLink("Click ME", "Controller", "Home", new { id = Model.id }, new { onclick = "stayHomeFunc()"})%></div>
After a review, I have to add a DatePicker function that allows the user to select a date. How do I get to pass that date selection to my controller? This is what I have so far, which returns a null startDate by the way...
Enter Date:<input name="DatePicker" id="DatePicker" type="text" style="width: 80px" />
<%= Html.ActionLink("Click ME", "Controller", "Home", new { id = Model.id, startDate = DatePicker }, new { onclick = "stayHomeFunc()"})%></div>
public ActionResult COntroller(string id, string startDate){...}
Any ideas? Thanks in advance...
You have 2 possibilities:
use a submit button inside the form containing the #DatePicker field. This way you don't need to pass anything, when the form is submitted all input values will automatically be sent to the server:
#using (Html.BeginForm("SomeAction", "Home"))
{
#Html.TextBoxFor(x => x.DatePicker)
<input type="submit" value="Click Me" />
}
if you want to use an anchor you will need to use javascript in order to append the value of the datepicker to the query string. So inside your stayHomeFunc function which is triggered when the link is clicked:
function stayHomeFunc(link) {
var date = $('#DatePicker').datepicker('getDate');
var formattedDate = $.datepicker.formatDate('yy-mm-dd', date);
link.href += '?DatePicker=' + formattedDate;
}
and then don't forget to pass the anchor instance to the onclick event:
<%= Html.ActionLink(
"Click ME",
"SomeAction",
"Home",
new { id = Model.id },
new { onclick = "stayHomeFunc(this)"}
) %>
Personally I would go with the first option as it is semantically more correct and doesn't require any javascript.
Also be careful with the DateTime format that the model binder uses and the differences that exist between GET and POST requests. For more information refer to the following article.
You can also use FormCollection.
VIEW
#using (Html.BeginForm("SomeAction", "Home"))
{
<input type="text" id="DatePicker" name="date">
}
CONTROLLER
public ActionResult SomeAction( FormCollection form)
{
var date = form["date"];
if (date != String.Empty)
{
MyModel model = new MyModel();
model.date= DateTime.Parse(date);
}
return RedirectToAction("YourNewAction", new {date = model.date});
}