I have a DropDownList which has a Car models
#Html.DropDownList("Cars", (IEnumerable<SelectListItem>)ViewBag.Cars, "Select a Value", htmlAttributes: new { #class = "form-control" })
i need the user must select a value also if he select a specific value send the id of the value to url to the action as a parameter
Modify Registration
Cancel Registration
You will need to use javascript to achieve this. So for example you could give your anchor an unique id:
<a id="editRegistration" href="#Url.Action("Edit", "Registration", new { id = "initial value from the database" })" class="text-white">Modify Registration</a>
and then subscribe to the change event of the dropdown and update the href of the anchor:
<script>
$('#Cars').change(function() {
var url = "#Url.Action("Edit", "Registration", new { id = "#ID#" })";
// replace the #ID# placeholder with the selected value
var newHref = url.replace('#ID#', this.value);
$('#editRegistration').attr('href', newHref);
// do the same with the other anchor
});
</script>
Related
I am using `#Html.Textbox("searchString") in Razor view page. I need this value of textbox in
#Html.ActionLink("View Items", "Index", new { id = item.transaction_id, searchString = "Value of textbox"}).
Of course the search string part in html action link is not working right now but i need this as i have specific route which works according to search string.
How do i pass value of textbox to action link?
i check this this,this,this and this.
What i tried is
<script type = "text/javascript">
var value = document.getElementbyID("searchString").Text;
var link = #Html.ActionLink("View Items", "Index", new { id = item.transaction_id, searchString = -1});
link.replace(-1,value);
</script>
Still no luck. I understand Razor renders at server side.
UPDATE
i have following textbox on the top of view:
#using (Html.BeginForm("Index", "trans_junction", FormMethod.Get))
{
<p>
Request No: #Html.TextBox("searchString")
<span><input type="submit" value="Search Request" /></span>
</p>
}
This textbox is search box in which user can search items.
there is an Action link as follows:
#Html.ActionLink("View Items", "Index", new { id = item.transaction_id }) |
and a route config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}/{searchString}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, searchString= UrlParameter.Optional }
);
}
}
Now i need to pass the values as my route map via actionlink. As suggested in answer by StephenMuecke, i tried to modify my #using (Html.BeginForm("Index", "trans_junction", FormMethod.Get)) with #using (Html.BeginForm("Index", "trans_junction", new { id = item.transaction_id }, FormMethod.Get))
but item is not accessible there.
When user click search button, url is http://localhost:57286/trans_junction/Index?searchString=20
if user click on Action link url is http://localhost:57286/trans_junction/Index/88
but i actually need is http://localhost:57286/trans_junction/Index/88/20
which preserve the the result of search and also pass the id.
I am adding screenshots for better understanding.
This is index view without search.
This is search result with searchString = 10.
This is after clicking the action link i.e. View Items, Here search results are not preserved.
Rather than manually trying to manipulate a link using javascript, use a form with method="get". Inside your loop
#using (Html.BeginForm("Index", "trans_junction", new { id = item.transaction_id }, FormMethod.Get))
{
#Html.TextBox("SearchString")
<button type="submit">View Items"</button> // style as a link if desired
}
which will make a GET call to
[HttpGet]
public ActionResult Index(int id, string searchString)
which assumes you have a specific route definition with
url: "trans_junction/Index/{id}/{searchstring}",
defaults: new { controller = "trans_junction", action = "Index" }
Edit (based on updated question details)
When your returning the filtered results, you will also need to pass back the value of searchString to the view so that in can be used to generate the route value in the ActionLink() methods, for example
ViewBag.Filter = searchString;
return View(....);
and then modify the links to
#Html.ActionLink("View Items", "Index", new { id = item.transaction_id, searchString = ViewBag.Filter })
You need to set the value on an event such as clicking on the ActionLink otherwise how do you know the value of the searchString textbox to replace in the Actionlink. Add this javascript on your page.
$(function(){
$("#myLink").click(function(){
var link = $(this).attr("href");
link.replace(-1, $(#searchString).val());
var link = $(this).attr("href", link);
});
});
And you Razor view actionlink needs to be
#Html.ActionLink("View Items", "Index", new { id = item.transaction_id, searchString = "-1"})
Try:
#{
var value = Request.Form["inputID"];
}
p.s. why aren't you using a form in stead of the link and submit the form when someone enters a searchString?
whoever downvoted this answer you could argument why or come up with a better solution? because in his case, searchString = Request.Form["inputID"]; should do what he is asking for.
I'm trying to dynamically set the StudentIds by letting the user select check boxes for the reports they want. When they click the ActionLink, I use jQuery to set the values of the ids in a hidden field. I need the Action Link to read the ids from hidden field.
The values are getting set in the hidden field, but they are not being passed to the controller from the actionLink.
I need to pass the ReportIds to the controller.
#Html.ActionLink("PrintMed", "GetMedEdVerificationReport", "Student", new { studentIdList = Model.ReportIds }, new { #class = "button print_selected print_selectedMedEd disabled" })
#Html.HiddenFor(model => model.ReportIds)
javascript
$('.print_selectedMedEd').bind('click', function () {
var ids = getPrintIds();
if (ids.length == 0) {
return false;
}
$('#ReportIds').val(ids.toString());
return true;
});
When the asp.net mvc render your ActionLink it will generate a link with a parameter that you have on the model. Event you change the value of the model, it will not change the value on the output generated by ActionLink.
Given this, you have to se again the value, try to generate an ACtionLink without the argument:
#Html.ActionLink("PrintMed", "GetMedEdVerificationReport", "Student", null, new { #class = "button print_selected print_selectedMedEd disabled" })
On the javascript side, you could try using the on method to bind a event handler and call the preventDefault method from the event argument, for sample:
$('.print_selectedMedEd').on('click', function (e) {
e.preventDefault();
var ids = getPrintIds();
if (ids.length > 0) {
$('##Html.IdFor(model => model.ReportIds)').val(ids.toString());
// make an url to redirect
var url = $(this).prop("href") + "?studentIdList=" + ids.toString();
// redirect using the generated url
window.location.href = url;
}
});
Remember to use the Html.IdForm() to make sure you have the right id for a specific property.
That is because #Html.ActionLinkdoesn't use the hidden fields to make the request. Once the action link renders it becomes
PrintMed
so you would need to modify the html on the anchor tag.
You should be using Html.Beginform instead in order to pass along the model.
#using (Html.BeginForm("GetMedEdVerificationReport", "Student", FormMethod.Post, null))
{
#Html.HiddenFor(model => model.ReportIds)
<input type="submit" value="PrintMed" />
}
#Html.HiddenFor(modelItem => item.OrderId)
<td>
<input type="button" value="Pickup" onclick="location.href='#Url.Action("Edit", "Assignment", new { ID = item.OrderId })'" />
I'm stuck with a very basic detail in a view.
I want to be able to let the user filter the results in the Index view.
To do this I've created a dropdown list, which gets populated thourgh my viewmodel:
#using (Html.BeginForm("Index", "Captains", FormMethod.Get)) {
<div class="row">
<div class="dropdown">
#Html.DropDownList("Name", new SelectList(Model.SomeProperty), new { id = "FilterList" })
</div>
</div>
#* ... *#
}
Additionally I have a small jQuery snippet to submit the form on the change event:
$('#FilterList').on('change', function () {
var form = $(this).parents('form');
form.submit();
});
The route I have created for this looks like this:
routes.MapRoute(
name: "IndexFilter",
url: "{controller}/{action}/{Name}",
defaults: new { Name = UrlParameter.Optional}
);
After the submit event I get redirected to the url /Index?Name=ChosenValue
This is filtering totally correct. However I'd like to get rid of the querystring and transform the route to /Index/ChosenValue.
Note: "Name", "ChosenValue" & "SomeProperty" are just dummy replacements for the actual property names.
Instead of submitting the form, you can concatenate /Captains/Index/ with the selected value of the dropdown and redirect to the url using window.location.href as below
$('#FilterList').on('change', function () {
window.location.href = '/Captains/Index/' + $(this).val();
});
I think you're looking for the wrong routing behavior out of a form submit. The type of route resolution that you're hoping to see really only happens on the server side, where the MVC routing knows all about the available route definitions. But the form submission process that happens in the browser only knows about form inputs and their values. It doesn't know that "Name" is a special route parameter... it just tacks on all the form values as querystring parameters.
So if you want to send the browser to /Index/ChosenValue, but you don't want to construct the URL from scratch on the client, you need to construct the URL on the server when the view is rendering. You could take this approach:
<div class="row">
<div class="dropdown">
#Html.DropDownList("Name", new SelectList(Model.SomeProperty),
new {
id = "FilterList",
data_redirect_url = #Url.Action("Index", "Captains", new { Name = "DUMMY_PLACEHOLDER" })
})
</div>
</div>
Above you're setting the URL with a dummy "Name" value that you can replace later, then you'll do the replacement with the selection and redirect in javascript:
$('#FilterList').on('change', function () {
var redirectUrl = $(this).data('redirect-url');
window.location.href = redirectUrl.replace("DUMMY_PLACEHOLDER", $(this).val());
});
If you are wanting to drop the query string off the url because it looks weird, then change your FormMethod.Post.
However, to really answer your question, I've tried the following successfully (Note: this might be considered a hack by some)
In short: update the action url on the form element when the list changes, client side.
$('#FilterList').on('change', function () {
var form = $(this).parents('form');
var originalActionUrl = form.attr("action");
var newActionUrl = originalActionUrl + "/" + $(this).val();
form.attr("action", newActionUrl);
console.log(form.attr("action"));
form.submit();
});
You will need to change your controller's signature to match whatever optional param value you specify in your route config. In your example, "Name".
I have the following situation:
Into a view I define a link in this way:
<a href="#Url.Action("Edit", "Vulnerability", new { id = Model.Id })" data-mini="true" data-inline="true" data-role="button" >Annulla</a>
As you can see when the user click the link it is executed the Edit() method ot the VulnerabilityController class passing and Id value
Ok, this works fine but in this view I want have something like I have in a controller, this thing:
return new RedirectResult(Url.Action("Edit", "Vulnerability", new { id = vulnId }) + "#tab-2");
As you can see in this second version I always call the Edit() method of the VulnerabilityController class but the value of Id variable is something like "1234#tab-2"
Can I do something like this in my view and not only in my controller?
If you want to render (include) the results of some action inside your View you can use Html.Action:
#Html.Action("Edit", "Vulnerability", new { id = vulnId + "#tab-2" })
See MSDN
For doing this using Razor Syntax, you can try like this:
#Html.ActionLink("Annulla", "Edit", "Vulnerability", new { id = Model.Id },
new{ #data_mini="true", #data_inline="true", #data_role="button"})
Note - this is an asp.net MVC 4 application using Razor 2 views...
basically I have a textbox in a view waiting for the user to input data,
this data makes up the values for properties of a model which I want to save to the Db.
The data associated with this textbox has a [required] tab in the Model. I cannot save the model without a value for this textbox as the Model is not valid.
I know I can simply add #Value to the #HtmlTextBoxFor line, put this means that value is displayed to the user.
Is there away to have a default value hidden, so that the user only see's the placeholder text but the "value" will be saved to the Db.
Any ideas...?
textbox..
#Html.TextBoxFor(n => n.Article.Title, new { #class = "span4 m-wrap", rows = 1 , #placeholder = "Enter your News Articles main subject or Title here" , #Value = "Title"})
controller
if (ModelState.IsValid)
NewsArticle newNews = new NewsArticle();
newNews.Title = newsArticle.Article.Title;
You can add an ID to the textbox as follows:
#Html.TextBoxFor(n => n.Article.Title, new { #class = "span4 m-wrap", rows = 1 , #placeholder = "Enter your News Articles main subject or Title here" , #Value = "", #id="txtTitle"})
Then call following jquery function on form submit event
$(function(){
$("form").submit(function () {
if($("#txtTitle").val() == ""){
$("#txtTitle").val("Default Value");
}
});
});