ASP.NET MVC - Loading dropdownlists based on selected value - asp.net-mvc

I have a view that looks somewhat similar to this
<% using (Html.BeginForm()) {%>
<%= Html.DropDownList("Category") %>
<%= Html.DropDownList("SubCategory") %>
<input type="submit" value="Print" />
<%= Html.ActionLink("Cancel", "Index") %>
<% } %>
I was wondering if anyone knew how i could load the subcategory based on the selected Category?
In webforms i'd just use the autopostback event to do this, but i'm a bit confused on how to do this using the mvc framework.
Thanks in advance

transform your view like this:
<% using (Html.BeginForm()) {%>
<%= Html.DropDownList("Category", Model.SelectList, new {onchange = "actualize(this);"}) %>
<div id="selectdiv">
<% Html.RenderPartial("SubCategories"); %>
</div>
<input type="submit" value="Print" />
<%= Html.ActionLink("Cancel", "Index") %>
<% } %>
<script type="text/javascript">
function actualize(obj)
{
$.ajax({
url: url,
async: true,
type: 'POST',
data: { id: obj.value },
dataType: 'text',
success: function(data) { $("#selectdiv").html(data); },
error: function() {
console.log('Erreur');
}
});
}
</script>
create a control called SubCategories.aspx and include in it:
<%= Html.DropDownList("SubCategory",Model.SelectList) %>
create a Model class
public class MyModel
{
public SelectList SelectList {get;set;}
}
create a controller action
public ActionResult SubCategories(int id)
{
MyModel model = new MyModel();
model.SelectList = new SelectList(YourRepository.GetSubCategories(id),"Id","Name");
return View(model);
}

Place the dropdown list within a PartialView. Then when you post back do a return PartialView("viewName", model). Then in the return of your jQuery simply replace the partial view with the new html that is returned.
So you're view;
<div id="myPartialView">
<% Html.PartialView("PartialViewName", model); %>
</div>
Then your jQuery does something like
$('#myPartialView').html = retHtml;
Your C#
return PartialView("PartialViewName", model);
Untested but that's the approach i think you want to take.

Related

How to send group of data so it will be binded in Controller's action?

How I need to send the data from the client in order to get it in Save action?
Mean while the contacts list I get in Save action is null.
I checked fiddler and it sends id=1&address=a&id=2&address=b. I realize that I need to do something in order that MVC will "understand" that there are 2 different records.
What is done, in practice, in this case?
// Action in ContactController
public ActionResult Save(List<Contact> contacts)
{
...
}
public class Contact
{
public int Id {get;set;}
public string Address{get;set;}
}
// View
<div id="contacts">
<% for(i=0;i<3;i++) { %>
<input name=<%= list[i].id %> type="text" />
<input name=<%= list[i].address %> type="text" />
<% } %>
</div>
<script type="text/javascript">
var postData = $("#contacts").serialize();
$.ajax({
type: "POST",
url: url,
data: postData,
async: false,
success: function () { ... }
});
</script>
I would recommend you to use editor templates in your view instead of writing some for loops:
For example:
public ActionResult Save()
{
var model = Enumerable.Range(1, 3).Select(x => new Contact());
return View(model);
}
[HttpPost]
public ActionResult Save(List<Contact> contacts)
{
...
}
and in the view (which is strongly typed to IEnumerable<Contact>):
<div>
<% using (Html.BeginForm()) { %>
<%= Html.EditorForModel() %>
<input type="submit" value="OK" />
<% } %>
</div>
and inside the contact editor template (~/View/Shared/EditorTemplates/Contact.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<Contact>"
%>
<%= Html.TextBoxFor(x => x.Id) %>
<%= Html.TextBoxFor(x => x.Address) %>
Editor templates will ensure to generate proper names for the input fields.
Now all that's left is AJAXify the form:
$('form').submit(function() {
$.ajax({
url: this.action,
type: this.method,
traditional: true,
data: $(this).serialize(),
success: function(result) {
...
}
});
return false;
});
In your example, if you change manual creation to Html.TextBoxFor
<% Html.TextBoxFor(model => list[i].Address) %>
It will work. Take a look at Phil Haack's article

Dynamically adding dropdowns to a form and validating them in ASP.NET MVC

I have a form with various inputs. I have a bunch of optional parameters that have some number of choices. I'd like to allow the user to select these optional parameters in the following way:
First, the user clicks the Add Component button at the bottom of the form and two new dropdowns appear above the button. The first dropdown has a list of Types that can be selected and the second one will be disabled. When the user selects a valid choice in the first dropdown, I want to populate the second dropdown with some Values that are specific to the specified Type. The user should be able to continue adding new Components (the pair of dropdowns) until all the desired optional Components are added. Ideally the form wouldn't be posted until all the fields have been filled out and the desired Components added.
My question is this: How do I design this so that when the form is submitted and there are errors, that the dynamically added fields (the Components) will remain on the page and display the correct values?
I was planning on having the Add Component button be an Ajax.ActionLink that retrieves a partialview:
<div id="divComponentHolder"></div>
<%= Ajax.ActionLink("Add a Component", "GetComponentSelector", new AjaxOptions { UpdateTargetId = "divComponentHolder", InsertionMode = InsertionMode.InsertAfter}) %>
This partial view would look something like this:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MVCAndWebFormsTest.Models.ComponentSelectorModel>" %>
<%= Html.Encode("Type:")%>
<%= Html.DropDownList("ComponentType", Model.ComponentTypes, "", new {onchange = "updateCompValues(this);"}) %>
<%= Html.Encode("File/Folder:")%>
<div id="selectdiv">
<% Html.RenderPartial("ComponentValueSelector", Model.ComponentValues); %>
</div>
<br/>
<script type="text/javascript" language="javascript">
function updateCompValues(obj) {
$.ajax({
url: <% Url.Action("GetCompValues") %>,
async: true,
type: 'POST',
data: { type: obj.value },
dataType: 'text',
success: function(data) { $("#selectdiv").html(data); },
error: function() {
console.log('Erreur');
}
});
}
</script>
And the ComponentValueSelector partial would be pretty simple:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MVCAndWebFormsTest.Controllers.ViewModels.ComponentValueModel>" %>
<%= Html.DropDownList("CompValue", Model.SelectList) %>
Take a look at submitting list in MVC, here are a few useful sites:
http://blogs.teamb.com/craigstuntz/2009/02/11/38013/
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx
This is useful for submitting your dynamic DOM you are building up.
Another way instead of making an ajax call to render a partial view you could always directly add elements to the DOM with jquery. For example use the jquery clone ( $('element').clone(); ) method that would copy your list boxes then do some regex to change the id's of the input boxes so they have unique id/names.
As you are passing through a List of these 'choices' to your controller, you would then have to set them back in your Model and have your View iterate through them to display the correct amount of choices added.
Here is a bare bones example. This may not be the best implementation for yourself or someone else may have better ideas.
View
<% for (int i = 0; i < in Model.Results.Count; i++) { %>
//render better HTML but you should get the point!
<%= Html.Hidden("choices[" + i + "].ID", i) %>
<%= Html.DropDownList("choices[" + i + "].Choice1", ...) %>
<%= Html.DropDownList("choices[" + i + "].Choice2", ...) %>
<% } %>
- add button
jQuery
$('#addButton').click(function()
{
//say if your choice drop downs were in a table then take the last
//row and clone it
var row = $('table tr:last').clone(true);
var newId = //work out the new id from how many rows in the table
//make sure to update the id and name parameters of inputs
//of the cloned row
row.find(':input')
.attr('id', function()
{
return $(this).attr('id').replace(/\[[\d+]\]/g, '[' + newlId + ']');
//this replaces the cloned [id] with a new id
})
.attr('name', function()
{
return $(this).attr('name').replace(/\[[\d+]\]/g, '[' + newId + ']');
});
row.find(':hidden').val(newId); //update the value of the hidden input
//alert(row.html()); //debug to check your cloned html is correct!
//TODO: setup ajax call for 1st drop down list to render 2nd drop down
$('table tr:last').after(row);//add the row
return false;
});
Controller
public ActionResult YourMethod(IList<YourObject> choices, any other parameters)
{
YourViewModel model = new YourViewModel();
model.Results = choices; //where Results is IList<YourObject>
return View(model);
}
Based on advice from David Liddle, I found a different design that was a bit more elegant. It uses more jQuery and fewer partial views and Ajax requests.
Instead of adding a bunch of DropDownLists, I decided to go with a table, a pair of dropdowns and an "Add" button. When the user selects a Type option in the first dropdown, ajax is still used to retrieve the partial view for populating the second Value dropdown. Once a Value option has been selected, the user then clicks the Add button.
Using jQuery, two hidden inputs are added to the page. The naming convention in the links from David are used to name these elements (comps[0].Type and comps[0].Value). Also, a new row is added to the table with the same Type and Value for visual feedback to the user showing what has been added.
I also defined a Component class that just has Type and Value properties and added a List to the Model. In the view, I iterate over this list and add all components in the Model to the table and as hidden inputs.
IndexView
<table id="componentTable">
<tr>
<th>Type</th>
<th>Deploy From</th>
</tr>
<% foreach (Component comp in Model.comps) { %>
<tr>
<td><%= Html.Encode(comp.Type) %></td>
<td><%= Html.Encode(comp.Value) %></td>
</tr>
<% } %>
</table>
<div id="hiddenComponentFields">
<% var index = 0;%>
<% foreach (Component comp in Model.comps) { %>
<input type="hidden" name="comps[<%= Html.Encode(index) %>].Type" value="<%= Html.Encode(comp.Type) %>" />
<input type="hidden" name="comps[<%= Html.Encode(index) %>].Value" value="<%= Html.Encode(comp.value) %>" />
<% index++; %>
<% } %>
</div>
<%= Html.DropDownList("ComponentTypeDropDown", Model.ComponentTypes, "", new { onchange = "updateCompValues();"}) %>
<span id="CompValueContainer">
<% Html.RenderPartial("ComponentValueSelector", new ComponentValueModel()); %>
</span>
<span class="button" id="addComponentButton" onclick="AddComponentButtonClicked()">Add the File</span>
<span id="componentStatus"></span>
ComponentValueSelector PartialView
<%# Control Language="C#" Inherits="ViewUserControl<ComponentValueModel>" %>
<% if(Model.SelectList == null) { %>
<select id="CompValue" name="CompValue" disabled="true">
<option></option>
</select>
<% } else { %>
<%= Html.DropDownList("CompValue", Model.SelectList, "") %>
<% } %>
jQuery
function updateCompValues() {
$.ajax({
url: '<%= Url.Action("GetComponentValues") %>',
async: true,
type: 'POST',
data: { type: $("#CompValue").value },
dataType: 'text',
success: function(data) { $("#CompValueContainer").html(data); enable($("#CompValue")) },
error: function() {
console.log('Erreur');
}
});
}
function AddComponentButtonClicked() {
UpdateCompStatus("info", "Updating...");
var type = $("#ComponentTypeDropDown").val();
var value = $("#CompValue").val();
if (type == "" || value == "") { // No values selected
UpdateCompStatus("warning", "* Please select both a type and a value");
return; // Don't add the component
}
AddComponent(type, value);
}
function AddComponent(type, setting_1) {
// Add hidden fields
var newIndex = GetLastCompsIndex() + 1;
var toAdd = '<input type="hidden" name="comps[' + newIndex + '].Type" value="' + type + '" />' +
'<input type="hidden" name="comps[' + newIndex + '].Setting_1" value="' + setting_1 + '" />';
$("#hiddenComponentFields").append(toAdd);
// Add to page
// Note: there will always be one row of headers so the selector should always work.
$('#componentTable tr:last').after('<tr><td>'+type+'</td><td>'+setting_1+'</td>remove</tr>');
}
function GetLastCompsIndex() {
// TODO
alert("GetLastCompsIndex unimplemented!");
// haven't figured this out yet but something like
// $("#hiddenComponentFields input:hidden" :last).useRegExToExtractIndexFromName(); :)
}
function UpdateCompStatus(level, message) {
var statusSpan = $("#componentStatus");
// TODO Change the class to reflect level (warning, info, error?, success?)
// statusSpan.addClassName(...)
statusSpan.html(message);
}
Controller
public ActionResult Index() {
SelectList compTypes = repos.GetAllComponentTypesAsSelectList();
return View(new IndexViewModel(compTypes));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(Component[] comps, other params...) {
foreach(Component comp in comps) {
// Do something with comp.Type and comp.Value
}
return RedirectToAction(...);
}
public ActionResult GetComponentValues(string type) {
ComponentValueModel valueModel = new ComponentValueModel();
valueModel.SelectList = repos.GetAllComponentValuesForTypeAsSelectList(type);
return PartialView("ComponentValueSelector", valueModel);
}
IndexViewModel
public class IndexViewModel {
public List<Component> comps { get; set; }
public SelectList ComponentTypes { get; set; }
public IndexViewModel(SelectList types) {
comps = new List<Component>();
ComponentTypes = types;
}
}

Asp.Net Axaj.BeginForm & UpdateTargetId not working

I have this in HomeController:
public ActionResult Details(string id)
{
var customer = Customers.GetCustomersById(id);
return PartialView("CustomerDetails", customer);
}
And this in Index.aspx:
<div>
<% using (Ajax.BeginForm("Details", new AjaxOptions
{
UpdateTargetId = "customerDetails",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST"
}))
{ %>
<p>
Customer:
<%=Html.DropDownList("id")%></p>
<p>
<input type="submit" value="Details" /></p>
<% } %>
</div>
<div id="customerDetails">
</div>
And finally in CustomerDetails.ascx I have:
<fieldset>
<legend>Fields</legend>
<p>
Name:
<%= Html.Encode(Model.Name) %>
</p>
<p>
Credit:
<%= Html.Encode(Model.Credit) %>
</p>
<p>
CustomerID:
<%= Html.Encode(Model.CustomerID) %>
</p>
</fieldset>
<p>
<%=Html.ActionLink("Edit", "Edit", new { /* id=Model.PrimaryKey */ }) %> |
<%=Html.ActionLink("Back to List", "Index") %>
</p>
CustomerDetails.ascx was generated by right clicking on the Details-method and choosing "Add View", and selecting partial view and strongly typed view.
I'd want this to update the customer details in "Ajax-manner" inside a div called "customerDetails" inside Index.html. The problem is that after pressing Details-button, a new page is opened where with the correct details. The output page has no master page colors or layouts.
If I debug at Details-method, the contents of customer object is correct.
Any help appreciated!
/pom
The most likely culprit is that you aren't including MicrosoftAjax.js and MicrosoftMvcAjax.js on the page. This causes the javascript to fail because it can't find the necessary functions and the form submits normally instead through Ajax.

ASp.NET MVC: TryUpdateModel doesn't update all properties

I've got the following action:
public ActionResult Create()
{
var entity = new Employee();
TryUpdateModel(entity, new[] { "Person.Name", "Code", "CompanyID" });
if (ModelState.IsValid)
{
var result = Service.MergeEmployee(entity);
return RedirectToAction("List", new { success = true });
}
return View("Edit", new SupplierEmployeeModel() { Employee = entity });
}
What happens is that the property "Person.Name" doesn't get filled by the TryUpdateModel.
This is my form:
<fieldset>
<p>
<label for="Name"><%=Strings.NAME %></label>
<%= Html.TextBox("Person.Name", Model.Employee.Person.Name, new { Class = "text" })%>
<%= Html.ValidationMessage("Name", "*") %>
</p>
<p>
<label for="CompanyID"><%=Strings.SUPPLIER %></label>
<%= Html.DropDownList("CompanyID") %>
<%= Html.ValidationMessage("CompanyID", "*")%>
</p>
<p>
<label for="Code"><%=Strings.CODE %></label>
<%= Html.TextBox("Code", Model.Employee.Code)%>
<%= Html.ValidationMessage("Code", "*") %>
</p>
<p>
<%= Html.Hidden("ID", Model.Employee.ID)%>
</p>
<div id="tabs-DE-actions" class="ui-dialog-buttonpane ui-helper-clearfix" style="display: block;">
<button class="ui-state-default ui-corner-all" type="submit"><%=Strings.SAVE%></button>
</div>
</fieldset>
Any thoughts on why this is happening?
Thanks
Make sure the Person object is initialized in the Employee constructor; if it's null to begin with it is probably not updated properly.
public Employee()
{
Person = new Person();
}
Try this:
TryUpdateModel(entity,"Person", new[] { "Name", "Code", "CompanyID" });
In order to fill in Person.Name, the model binder has to create a new Person. Have you given the model binder enough info to do that? Alternately, try creating the Person yourself before binding.

ASP.NET MVC Passing Data from View to Controller

I have a view with a grid that contains items added to a workstation. The user can select an item from a drop down list and click an action link which calls a controller that adds that item to the workstation. I can make it work by reading the FormCollection object in the Post action of the controller.
<p>
<% using(Html.BeginForm("AddItem", "Home")) { %>
<label for="ItemID">Item:</label>
<%= Html.DropDownList("ItemID", Model.ItemsList) %>
<%= Html.Hidden("WorkstationID", Model.Workstation.RecordID) %>
<input type="submit" value="Submit" />
<% } %>
</p>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddItem(FormCollection formValue)
{
long workstationId = Convert.ToInt64(formValue["WorkstationID"]);
long itemId = Convert.ToInt64(formValue["ItemID"]);
Workstation workstation = itilRepository.FindWorkstation(workstationId);
Item item = itilRepository.FindItem(itemId);
itilRepository.AddItem(workstation, item);
itilRepository.Save();
return Content("Item added successfully!");
}
What I want to do is be able to submit the two parameters the workstationId and itemId to the controller using Ajax.ActionLink and have the new item that was added get inserted into the grid. I am rendering the grid like this:
<table>
<tr>
<th></th>
<th>
Name
</th>
<th>
Service Tag
</th>
<th>
Serial Number
</th>
</tr>
<% foreach (var item in Model.Items) { %>
<tr>
<td>
<%= Html.ActionLink("Edit", "ItemEdit", new { id = item.RecordID }) %> |
<%= Html.ActionLink("Details", "ItemDetails", new { id = item.RecordID })%>
</td>
<td>
<%= Html.Encode(item.Name) %>
</td>
<td>
<%= Html.Encode(item.ServiceTag) %>
</td>
<td>
<%= Html.Encode(item.SerialNumber) %>
</td>
</tr>
<% } %>
</table>
The problem I have is when I submit using the ActionLink I can't figure out how to pass in the parameters to the controller and how to update the grid without reloading the entire view.
I would really appreciate some help with this or even a link to a tutorials that does something similar.
Thank You!
This is the working version, the one problem is that when the controller returns the partial view that is all that gets rendred the actual page is gone.
<% using (Ajax.BeginForm("AddItem", null,
new AjaxOptions
{
UpdateTargetId = "ResultsGoHere",
InsertionMode = InsertionMode.Replace
},
new { #id = "itemForm" } ))
{ %>
<label for="ItemID">Item:</label>
<%= Html.DropDownList("itemId", Model.ItemsList) %>
<%= Html.Hidden("workstationId", Model.Workstation.RecordID) %>
Submit
<div id="ResultsGoHere">
<% Html.RenderPartial("WorkstationItems", Model.Items); %>
</div>
<% } %>
Not sure what the cause is, the replace was working correctly before but the controller wasn't getting the drop down value. Now the controller is getting the value but the partial view that is returned replaces the entire page.
The Action Method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddItem(string workstationId, string itemId)
{
long lworkstationId = Convert.ToInt64(workstationId);
long litemId = Convert.ToInt64(itemId);
Workstation workstation = itilRepository.FindWorkstation(lworkstationId);
Item item = itilRepository.FindItem(litemId);
IQueryable<Item> items = itilRepository.AddItem(workstation, item);
itilRepository.Save();
return PartialView("WorkstationItems", items);
}
This is the HTML for the View that does all the work:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ITILDatabase.Models.WorkstationFormViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Workstation Details
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<link type="text/css" href="/../Content/css/ui-lightness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />
<script type="text/javascript" src="/../Content/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/../Content/js/jquery-ui-1.7.2.custom.min.js"></script>
<h2>
Workstation Details</h2>
<fieldset>
<legend>Fields</legend>
<p>
Record ID:
<%= Html.Encode(Model.Workstation.RecordID) %>
</p>
<p>
Name:
<%= Html.Encode(Model.Workstation.Name) %>
</p>
<p>
Description:
<%= Html.Encode(Model.Workstation.Description) %>
</p>
<p>
Site:
<%= Html.Encode(Model.Workstation.Site.Name) %>
</p>
<p>
Modified By:
<%= Html.Encode(Model.Workstation.ModifiedBy) %>
</p>
<p>
Modified On:
<%= Html.Encode(String.Format("{0:g}", Model.Workstation.ModifiedOn)) %>
</p>
<p>
Created By:
<%= Html.Encode(Model.Workstation.CreatedBy) %>
</p>
<p>
Created On:
<%= Html.Encode(String.Format("{0:g}", Model.Workstation.CreatedOn)) %>
</p>
</fieldset>
<fieldset>
<legend>People</legend>
<% Html.RenderPartial("WorkstationPeople", Model.People); %>
</fieldset>
<fieldset>
<legend>Positions</legend>
<% Html.RenderPartial("WorkstationPositions", Model.Positions); %>
</fieldset>
<fieldset>
<legend>Items</legend>
<% using (Ajax.BeginForm("AddItem", "Home", null,
new AjaxOptions
{
UpdateTargetId = "ResultsGoHere",
InsertionMode = InsertionMode.Replace
},
new { #id = "itemForm" } ))
{ %>
<label for="ItemID">Item:</label>
<%= Html.DropDownList("itemId", Model.ItemsList) %>
<%= Html.Hidden("workstationId", Model.Workstation.RecordID) %>
Submit
<div id="ResultsGoHere">
<% Html.RenderPartial("WorkstationItems", Model.Items); %>
</div>
<% } %>
</fieldset>
<br />
<p>
<%=Html.ActionLink("Edit", "WorkstationEdit", new { id = Model.Workstation.RecordID }) %>
|
<%=Html.ActionLink("Back to List", "Index") %>
</p>
</asp:Content>
What result are you expecting from the AJAX call?
You could use the AjaxHelper object's helper methods instead of the HtmlHelper to render the link. For example, to get new content with an AJAX HttpPOST call and insert it into a <div> with the id set to ResultsGoHere you render the following link:
<%= Ajax.ActionLink("Edit", "ItemEdit",
new {
itemId = item.RecordId,
workstationId = myWorkStationId
},
new AjaxOptions {
HttpMethod="POST",
UpdateTargetId="ResultsGoHere",
InsertionMode = InsertionMode.Replace
}) %>
In your AcionMethod, you can simply test on Request.IsAjaxRequest() to decide what to return:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ItemEdit(string itemId, string workstationId) {
// edit the item and get it back
if (Request.IsAjaxRequest()) {
return PartialView("SingleItem", item);
}
return RedirectToAction("ItemEdit", new { itemId = item.RecordId, workstationId = workstationId });
}
// fallback for get requests
public ActionResult ItemEdit(string itemId, string workstationId)
{
// do stuff and return view
}
This is how you could do it using the Ajax.BeginForm() method instead:
<% using (Ajax.BeginForm("ItemEdit", null, new AjaxOptions
{
UpdateTargetId = "ResultsGoHere",
InsertionMode = InsertionMode.Replace
}, new { #id = "itemForm" } )
{ %>
<p>
<%= Html.DropDownList("itemId") %></p>
<p>
<%= Html.DropDownList("workstationId") %></p>
<p>
Submit
</p>
<% } %>
Please note that the code is in its current state in no way fully functional - the dropdownlists don't get their items from anywhere, there is no <div> to take care of the results from the AJAX request, and the onclick attribute on the link that submits the form requires that jQuery is included (in which case it is way better to give the link an id and add a click() event handler to it from a separate js file...)
EDIT: Oh, and I haven't verified that it is OK to pass a null value to the routeValues parameter. If not, just supply the controller and action names, and you'll be fine.
how can you pass the model from the view to the post create action of the controller using ajax.actionlink?
Here, as of my knowledge, we can pass data from View to Controller in two ways...
Using Formcollection built in keyword like this..
[HttpPost]
public string filter(FormCollection fc)
{
return "welcome to filtering : "+fc[0];
(or)
return "welcome to filtering : "+fc["here id of the control in view"];
}
FormCollection will work only when you click any button inside a form. In other cases it contains only empty data
Using model class
[HttpPost]
public string filter(classname cn)
{
return "welcome to filtering : "+cn.Empid+""+cn.Empname;
}
This is how you will be able to send multiple parameters through actionLink.
For this situation please refer to the code below:
#Html.ActionLink("Link text", "Action Name", null, routeValues: new { pram_serviceLine = Model.ServiceLine_ID, pram_Month = Model.Month, pram_Year = Model.Year, flag = "ROTATION" }
Reply if it works.

Resources