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
});
});
Related
In Asp.net MVC, Is it possible to have a form post to two different actions based on model value when clicked on the same button?
Ex. - I want to add a new customer or update an existing customer on click of the same button "Save". Can the form be posted to two different action methods based on the customer's id value.
if the customer id value = 0 , then post it to "Create" acction method , if the customer id value is already present (not equal to 0), then post the form to "Update" action method?
Is this possible in asp.net mvc?
No You cant call multiple action on submit with fairly way,
You need to add hiddenfield for id
<input type="hidden" name="id" value="#model.Id" />
When you submit the form the value will be retrieve from model
And check the hidden field value is 0 or not
If 0 than the entity needs to create else it is for update
public ActionResult Save(Customer customer){
if(customer.id > 0){
// Update Entity
}
else{
// Create Entity
}
}
Yes. It is possible. There are multiple ways to do it.
1) You can conditionally set the form action attribute value based on your view model property value.
<form method="post" action="#(Model.Id==0?Url.Action("Create","Home")
:Url.Action("Update","Home"))">
<input type="text" name="FirstName" />
<button type="submit">Save</button>
</form>
2) Another option is, you can add html5 formaction to your submit button and the value of that attribute could be the url to create or update action method based on your Id property value.
#using (Html.BeginForm("Create", "Home"))
{
<input type="text" name="FirstName" />
<button type="submit"
formaction="#(Model.Id==0?Url.Action("Create","Home")
:Url.Action("Update","Home"))">Save</button>
}
When you specify the formaction attribute on a submit button, it will overrides the parent form's action attribute value.
3) Another option is to hijack the form submit event in javascript, prevent the default behavior (stopping the form submit) and then update the form's action attribute value to /create or /update and trigger form submit using javascript. You can keep the Id property value in a hidden field inside the form and read the value of that and use that to determine what should be the url for the form's action attribute value.
Assuming you have a hidden element for the Id of type int property in your page
#model YourViewModel
#using (Html.BeginForm("Create", "Home",FormMethod.Post,new {id="yourFormId"}))
{
#Html.TextBoxFor(a=>a.FirstName)
<button type="submit">Save</button>
#Html.HiddenFor(a=>a.Id)
}
and the javascript to hijack the form submit and update the form's action attribute value would be like
$(function () {
$("#yourFormId").submit(function(e) {
e.preventDefault(); // stop the normal form submit
var id=parseInt($("#Id").val());
var url=$(this).attr("action");
if(id===0)
{
url='/Home/Update'; // Use the Url.Action to be safe to generate this
}
// read the data attribute and update the forms action and do a submit
$(this).closest("form").attr('action', url).submit();
});
});
4) Another option is always submitting the form to Update or Create action and inside that method, based on the the Id property value, execute the code for Update or Create as needed.
Yes. This for the View case:
#mode MyModel
#{
string action = Model.Id == 0 ? "Create" : "Edit"
}
#using (Html.BeginForm(action, "MyController"))
{
// if Edit need Id
if(action == "Edit")
{
#Html.HiddenFor(model=> model.Id)
}
#Html.TextBoxFor(model >= model.Name);
<input type="submit" value="Save">
}
Is there any way to pass the checkbox values to the controller on checking from a list of checkbox without using any submit button or any jquery Ajax? I just want to use only asp.net mvc property.
As user1576559 sad in comment:
I want to submit the form when I'll check or uncheck any of the
checkboxs without using any jquery or ajax
Here it is:
#using (Html.BeginForm("Update", "Home"))
{
<p>Checkboxes:</p>
#Html.CheckBox("chk1", new { onchange = "this.form.submit()" }); <br/>
#Html.CheckBox("chk2", new { onchange = "this.form.submit()" }); <br />
#Html.CheckBox("chk3", new { onchange = "this.form.submit()" }); <br />
}
As per my understanding, you need to use #Html.CheckboxFor(m=>m.PropertyName) when you send the page to server then you get the updated checkbox status.
In an MVC page several child action calls to my DropdownListController. The controller renders generic partial page with dropdown fields in my form. The partial page is listed below. The problem is tthat the he Html.DropdownListFor always generates the dropdowns with "SelectedItem" as the name even I specified the name in the HtmlAttribute parameter. How do I get this unique dropdown name for each child action call to the DropdownListController? In addition, the ValidateionMessageFor doesn't show either when the a value must be selected.
#model MyProject.ViewModels.DropDownListViewModel
#Html.DropDownListFor(m => m.SelectedItem, Model.Items, Model.Label, new { id=Model.ElementName, name = Model.ElementName})
#Html.ValidationMessageFor(m=>m.ElementName)
The DropDownListFor directive sets m.SelectedItem as the control's name + id. So why can't you just use the following?
#Html.DropDownListFor(m => m.ElementName, Model.Items, Model.Label)
I am using MVC Structure. I have to create a report which can be filtered by drop downs. I am thing to use a partial view to display report.
HEre is the structure of the page I want to achieve.
On top of page, there will be some drop down lists.
Below these will be page for report.
when user changes the options from dropdownlist, the report will be filtered.
I have two questions
1. How to render partial page.
2. How to refresh partial page through ajax/jquery. I want to do this on client side.
I have checked online, I am rendering page as shown in code below
VIEW
<h3>Report</h3>
<div>
<table>
<tr>
<td>ServiceLine</td>
<td>#Html.DropDownList("ServiceLine", null, new {id="ServiceLine"}) </td>
</tr>
</table>
</div>
<div>
<h2>List</h2>
<div>
#Html.Partial("PartialView")
</div>
</div>
This is what I have got in controller
public ActionResult PortfolioReport(char serviceLine)
{
//Department List
var serviceLines = Enum.GetValues(typeof(SogetiDepartments)).Cast<SogetiDepartments>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = ((char)v).ToString(),
});
foreach (SelectListItem item in serviceLines)
{
if (Convert.ToChar(item.Value) == serviceLine)
item.Selected = true;
}
ViewBag.ServiceLine = serviceLines;
return View();
}
Any kind of help is appreciated.
You have to use jQuery to achieve this feature
First apply some identifier to your data container
<div id="reportContent">
#Html.Partial("PartialView")
</div>
And then write script on your dropdown change event using jQuery
<script type="text/javascript">
$(function(){
$("#ServiceLine").change(function{
// get data from server using ajax
var url = 'YourPartialPageURL?'+serviceLine+="="+$(this).val();
$('#reportContent').load(url);
});
});
</script>
Note: You should use return PartialView(); from your controller action
And don't use #Html.Partial and use #Html.Action instead.
#Html.Partial loads View directly without going to Controller Action.
It should be used if you have data to be passed with you or if you just want to load some static content on the page
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();
}