I have a searchform in my mvc application where i choose in a dropdownlist what department i want to search in, and a textinput on what i want to search on.
when i choose a department in my dropdownlist i want to forms controller to change to the selected value.
Lets say i have these items i my dropdownlist: "Customers", "Products", "Invoices"
when i choose "Customers" in my dropdownlist i want my Html.BeginFrom to look like this:
<% using (Html.BeginForm("Customers", Request.QueryString["Search"], "Search", FormMethod.Get))
{ %>
and when i select "Products" i want "Customers" to change to "Products".
I agree this isn't the best way to approach things, however if you still need to do it this way then a simple jquery statement is what you'll need.
Basically handle the onSubmit action of the form (or the onChange of the dropdown list --both will work) and change the form's action based on the value of the drop down list
Something like this should work:
<% using (Html.BeginForm()) { %>
<%=Html.DropDownListFor( x => x.DepartmentList ) %>
<input type='submit' value='submit'/>
<% } %>
<script type="text/javascript">
$(function(){
$('#DepartmentList').change(function(){
$('form').attr('action', $('#DepartmentList option:selected').val() );
});
});
</script>
Check out the answer of this question for more details
This is generally not the way you do things.
If you need two different things to happen depending on the posted value of a dropdown you should handle the logic dispatching inside of the Controller.
public ActionResult DoSomething(string actionType )
{
if( actionType == "Products" )
DoSomething();
if( actionType == "Customers" )
DoSomethingDifferent();
}
Related
I am using this code to post value of selected item from the view to the controller
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.MyVar, (SelectList)ViewData["List"])
<button name="Button" value="Valider">Valider</button>
}
Is there a way to send the value when the selection change in the select list (without the need to click on the button) ?
If you name the SelectList in the ViewData the same as the name of the variable in your Model, MVC will figure the rest out for itself.
So your dropdown would look like:
#Html.DropDownList(ViewData.MyVar, String.Empty)
This is as opposed to naming your ViewData item 'List'.
yes you can do it via JQUERY, on dropdown selection change post the form via jquery:
add id to drop down:
#Html.DropDownListFor(model => model.MyVar, (SelectList)ViewData["List"], new { id="SomeId"})
and write jquery event:
$(function(){
$("#SomeId").change(function(){
$(this).closest("form").submit(); // this will post the form
});
});
I have the following form:
<li>
<% using (Html.BeginForm("TestMethod", "MyController", FormMethod.Post, new {id = "TestMethod"}))
{%>
<%= Html.Hidden("model", Model.MyListOfObjects) %>
<%}%>
Test
</li>
And the javascript function for the onclick is as follows:
function SubmitForm() {
document.forms["TestMethod"].submit();
}
I am trying to pass the list of objects from the view into the controller, but i have yet managed to get this to work. My Controller function is:
[Authorize]
[HttpPost]
public ActionResult TestMethod(List<Objects> model)
{
dynamic Expando = new ExpandoObject();
Expando.test = model;
return View(Expando );
}
When I view the List of objects in the debugger it always displays "System.Collections.Generic.List`1[]" with no actual objects inside.
So my question is what should I be doing to pass a List of objects into a controller?
I have also tried:
<% using (Html.BeginForm("TestMethod", "MyWork", FormMethod.Post, new {id = "TestMethod"}))
{%>
<% int itemx = 0; %>
<% foreach (var x in Model.MyListOfObjects)
{%>
<%= Html.Hidden("model"+"["+itemx+"]", x) %>
<%itemx++; %>
<% } %>
<%}%>
You cannot just put List<object> as action parameter and expect the model binder to be able to automagically guess what object types you want to put there. You will need to write a custom model binder if you wanted to handle multiple sub-types as illustrated in this post.
And if you want to use a single type for the list such as List<MyViewModel> then simply loop through each element of the list (respecting the convention) and for each element build a hidden field for each property that you want to bind.
But since those are hidden fields, I guess that the user is not supposed to modify them. In this case those hidden fields have nothing to do in your view. Let's not reinvent the ViewState that we were all so happy to get rid of when we moved to ASP.NET MVC from classic WebForms. Simply put a hidden field containing an unique id that will allow you to refetch the corresponding list elements in the POST action given this unique id from wherever you fetched them initially (your database or something I suppose).
You need to have one hidden element for each object in the list, and named model[0], model[1], etc.
I'm trying to create an ActionLink in one of my views that sends the selected value of a dropdown list to a new action. So far I have this, I just need to find a way to populate the ID on the end of my ActionLink.
<%= Html.DropDownList("StatusDropDown") %>
<%= Html.ActionLink("Apply","Index",new {Controller="Tasks", Action="Index", id="DROPDOWN LIST SECLECTED VALUE"}) %>
Obviously this link would need to be updated whenever the selected index of the drop down is changed. Is this something I need to do in javascript or is there a better way of managing this from within ASP.Net MVC?
Thanks
If you don't want to use form submission (i.e., want the parameter passed as part of the url instead of a form parameter), you'll need to build the url client-side with javascript.
<%= Html.DropDownList("StatusDropDown") %>
<a id="applyLink" href="#">Apply</a>
<script type="text/javascript">
function setHref( elem, val )
{
if (val) {
$(elem).attr( "href", "/Tasks/" + val );
$("#applyLink").unbind("click");
}
else {
$(elem).attr( "href", "#" );
$("#applyLink").click( function() { alert( "No value chosen" ); } );
}
}
$(function() {
var dropdown = $("#StatusDropDown");
dropdown.change( function() {
setHref( this, $(this).val() );
});
setHref( dropdown, null );
});
</script>
A link goes to another page, it is in effect a redirect. The only way to update where that link goes to with reference to the drop down list is with javascript.
It sounds like you want a kind of submit action. In that case you should use a form and a submit button, creating the appropriate handlers in your controller. Remember you can just do a redirect in your controller based upon the submitted value of the form. So something like this:
<form method="post" action="/MyForm">
<input type="select" name="mySelect">
<option value="1">First Option</option>
<option value="2">Second Option</option>
</input>
</form>
And in your controller:
public ActionResult MyForm(int mySelect)
{
return Redirect(String.Format("myurl?id={0}", mySelect));
// Note the above is only preferable if you're going to an external link
// Otherwise you should use the below:
return RedirectToAction("myAction", new { id = mySelect });
}
Obviously in this simplified example, the MyForm proxy to your desired action is redundant, but it illustrates the idea so you can apply it to your specific situation.
I'm new to MVC and I'm involved in a project that is developed with ASP.NET MVC 1.0. I'm also weak in JavaScript :-(
I'm trying to demonstrate how Master-Details view work on 'Orders' & 'Order Details' tables from Northwind database. (Hence: the tables has a relation, i.e., an order can have multiple order details)
I created two controls (1st for Orders, 2nd for OrderDetails). I displayed all the orders from Orders table into a List view. Once I click on one of the orders it takes me to the Details view of that order.
What I want to do (& failed) is to create a sub view below the Details view of the order that is having all the order details for that order.
I also want to change the content of the sub view based on the selections from the master view. I read a lot about using AJAX & JSON to dynamically change that but I failed to do it too :'(
Anyone can help in that and provide me with the technique & code of how I can implement it?
You can do this fairly easily with MVC and jQuery.
First in your Orders\List.aspx view:
<script>
// once the page has loaded
$(function() {
// set up your click event to load data
$('.list-item').click(function() {
// ajax load the content returned by the detail action
$('#detail').load('<%= Url.Action("Detail") %>', { id: this.id } );
});
});
</script>
<style> .list-item { cursor: pointer; } </style>
<% // loop through the orders in your model and show them
// as each div has the class list-item it will be give the click event
foreach( var order in Model ) { %>
<div id="<%= order.Id %>" class="list-item"><%= order.Name %></div>
<% } %>
<%-- the panel that the ajaxed content will be loaded into --%>
<div id="detail"></div>
Then in your Orders\Detail.ascx partial view:
Id: <%= Model.Id %><br />
Name: <%= Model.Name %><br />
Description: <%= Model.Description %><br />
etc
Inside of an asp.net mvc partial view, I have an Ajax form that posts a value and replaces the contents of its parent container with another instance of the form.
Index.aspx view:
<div id="tags">
<% Html.RenderPartial("Tags", Model); %>
</div>
Tags.ascx partial view:
<% using(Ajax.BeginForm("tag", new AjaxOptions { UpdateTargetId = "tags" }))
{ %>
Add tag: <%= Html.TextBox("tagName")%>
<input type="submit" value="Add" />
<% } %>
The controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Tag(string tagName) {
// do stuff
return PartialView("Tags", ...);
}
The problem is when the new instance of the form returns, the posted value is already stored in the input field. As in, whatever I posted as the 'tagName' will stay in the textbox. Firebug shows that the value is hardcoded in the response.
Is there any way to clear the input textbox's value when returning the partial view?
I've tried:
<%= Html.TextBox("tagName", string.Empty)%>
and
<%= Html.TextBox("tagName", string.Empty, new { value = "" })%>`
neither of which do anything.
EDIT:
I realize there are js solutions, which I may end up having to use, but I was wondering if there were any ways of doing it in the backend?
I'm not sure if this solution is "good enough" for you, but couldn't you just empty the form in a JS callback function from your ajax call? If you're using jQuery on your site, the callback function could look something like this:
function emptyFormOnReturn() {
$(':input').val();
}
I am not entirely sure if it will, but in case the above code also removes the text on your submit button, change the selector to ':input[type!=submit]'.
yes you should use jquery to set values on response
if you change your code to use jquery for ajax operations, you can call you settingvalues function on success callback...example:
http://docs.jquery.com/Ajax/jQuery.ajax#options