Getting Selected Item From a Dropdown MVC - asp.net

I created a dropdown like this:
<%= Html.DropDownList("Nick") %>
When a user selects an item I wanna send the text of the item back to a controller Action. I am guessin I add the same name of the the get controller with an [HTTPPOST] attribute, but how do I pass the selected item text into the controller?
I want this 2 happen in 2 scenerios
-When a user selects an item
-Add a button to the html (im not sure the best way??) and when a user clicks the button
the dropdowns selected text is sent.
I am populating the dropdown from ViewData["items"] i populated in the controller.

You need a form. You need to populate the drop down. And if you want the form to be sent as soon as the item is selected, you need half a line of javascript.
<% using (Html.BeginForm()) { %>
<%: Html.DropDownList("nick",
new SelectList[] { new[] { "hello", "world", "wazza" } },
new { #onchange = "this.form.submit()" })%>
<% } %>
You may also want your controller to receive a value rather than the text in the list option. See the SelectList class for more details.

Have your form submit to this action.
public ActionResult MyAction(string nick)
{
//do stuff
}

Related

Rendering partial view dynamically in ASP.Net MVC3 Razor using Ajax call to Action

I'm trying to create a single page form to create a 'work item'. One of the properties is a drop down for 'work item type'.
Depending on the work item type, the user may need to provide additional information in a name-value-pair style attributes grid (property sheet).
I would like to dynamically render the property sheet as soon as a work item type is selected or changed. Once the user provides all information, he would click submit to create the 'work item'.
This is what I have so far:
#using (Ajax.BeginForm("AttributeData", new AjaxOptions() { UpdateTargetId="AttributeDataCell" }))
{
<div style="float:left">
#{
Html.RenderPartial("CreateWorkItemPartialView");
}
</div>
<div id="AttributeDataCell" style="float:right">
#Html.Action("AttributeData", new {id = 1})
</div>
}
The AttributeData action in the controller simply renders the partial view:
public ActionResult AttributeData(int id = 0)
{
var attributes = _workItemDataService.ListWorkItemTypeAttributes(id);
return PartialView("EditWorkItemAttributesPartialView", attributes);
}
Now I would like to hook this up to the drop-down-list's selection event so that the partial view re-renders in the above table cell at every selection change. I would like to pass in the selected value as id.
One way is to force the form to submit itself (and thus re-render).
If that is the right approach, how do we go about it? Esp., how do we make only the property sheet to re-render?
If there is a better way to achieve the above, please indicate.
Thanks
You could subscribe to the .change() event of the dropdown and trigger an AJAX request:
$(function() {
$('#Id_Of_Your_Drop_Down').change(function() {
// This event will be triggered when the dropdown list selection changes
// We start by fetching the form element. Note that if you have
// multiple forms on the page it would be better to provide it
// an unique id in the Ajax.BeginForm helper and then use id selector:
var form = $('form');
// finally we send the AJAX request:
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(result) {
// The AJAX request succeeded and the result variable
// will contain the partial HTML returned by the action
// we inject it into the div:
$('#AttributeDataCell').html(result);
}
});
});
});

Display selected check box values in MVC3

I have a view in MVC3, that has bunch of check boxes. The user checks one or more check boxes and clicks on submit. On submit, I would like to display the checked boxes values in a partial view or a view.
<table>
<tr><td> #Html.Label("Label1")</td><td> #Html.CheckBox("CB1")</td></tr>
<tr><td> #Html.Label("Label2")</td><td> #Html.CheckBox("CB2")</td></tr>
<tr><td> #Html.Label("Label3")</td><td> #Html.CheckBox("CB3")</td></tr>
</table>
#Html.ActionLink("Submit", "SubmitCB")
Controller action:
public ActionResult SubmitCB()
{
#foreach (var checked in ?)
{
//Display checked only here...
}
}
I was wondering how I can loop through and display the results in a partial view or a view. Thanks for your help.
You need to change your action to allow it to bind to the submitted form. Also, you need to submit the form properly (I would suggest wrapping it in a form tag and using a submit button as opposed to an action link. But here's what your action would look like:
public ActionResult SubmitCB(bool CB1, bool CB2, bool CB3)
{
... // use CB1, CB2, and CB3 here
}
If you'd like these checkboxes to be in a list, you need to give them all the same name and different values. Then You can have your action take in something like SubmitCB(string[] CBs) and look at the values in that array (they'll be the values of the selected checkboxes).

How to pass parent model from inside partial view

I am rendering a parital view which has a submit button with HttpPost action in controller. This action method needs parent model as its parameter. Is there any way to send parent model as first parameter from inside a partial view?
Main view -> aspx file which has model as ParentModel
Partial view -> ascx file which has model as ParentModel.ChildModel
Controller action -> MyActionName(ParentModel model, int direction, int user)
If I keep the method as HttpPost then by default Parent model gets passed but then I cannot send 2nd and 3rd parameter as their values are decided at run time and these are not childmodel properties. e.g. direction parameter which indicates if user has clicked next/prev button. In this case, next and prev buttons call same action method (MultipleAction submit)
Additional info: My parent model has a collection of child model. I am looping through this collection and calling RenderPartial for each item. So, I cannot pass this parent model directly to my partial view (which is default behavior).
Any suggestions please? Thanks..
You could wrap all those partials into a HTML <form> so that all values get submitted too the server when this form is posted:
<% using (Html.BeginForm()) { %>
<%= Html.TextBoxFor(x => x.SomePropertyOfParent) %>
<%= Html.TextBoxFor(x => x.SomeOtherPropertyOfParent) %>
<%= Html.EditorFor(x => x.Children) %>
<input type="submit" value="OK" />
<% } %>
I use an editor template instead of partials for the Children collection. The custom editor template will automatically be rendered for each element of this children collection and provide any input fields allowing to modify it.
Then when the form is finally submitted all the properties required by the model binder to reconstruct the ParentModel will be sent to the server. As far as the direction and user parameters are concerned I would make them part of the parent view model so that my POST controller action looks like this:
[HttpPost]
public ActionResult MyActionName(ParentViewModel model)
{
...
}

Updating viewmodel data in controller doesn't reflect in view's input fields

I have a blogpost edit page where you can either save your edits or upload an image (multiple submits in a single form). When you upload an image, the image link gets appended to a TinyMCE content area.
The fields for the form are in a viewusercontrol(shared with create page). Both the viewpage and usercontrol inherit from BlogPost so the model's being passed directly using <% Html.RenderPartial("Fields", Model); %>
So here's the weird thing; in my controller, when I append the image link to the textarea, nothing happens to the textarea in the view
On my viewpage I have a label for Model.Title and within the usercontrol I have the textbox for editing Model.Title.
If I update the label in the controller - model.Title = "New Title" - the updated model data changes for the label in the viewpage but not the textbox in the usercontrol.
My Controller is like this:
// /edit/{id}
public ViewResult Edit(int id, BlogPost model, string submit)
{
if (ModelState.IsValid)
{
switch (submit)
{
case "Upload":
var files = UploadFiles(Request.Files); // uploading works
model.Content += files[0].Link; // model is updated but not cascaded at runtime
model.Title = "Test"; // Force a title change to reproduce the issue
return View(model);
default:
repository.Update(model);
break;
}
}
return View(model);
}
Any ideas as to what's causing this and how to fix it? Thanks.
I am using 4.0 and MVC 2
Turns out that this behaviour is by design and has been answered by Phil Haack here:
Possible bug in ASP.NET MVC with form values being replaced.
There's also a blog post about this here:
ASP.NET MVC’s Html Helpers Render the Wrong Value!
For my scenario (appending an image to tinymce), I think it's safe to clear the ModelState because we're explicitly appending to a textarea and not doing any validation yet.
Is there any chance that there is code in the top level view that is changing the value of Model.Title before the RenderPartial is called?

Ajax update after Delete action on Index view in ASP.MVC

I'm trying to do an Ajax delete in a fairly standard Index view, i.e. I have a generated Index view with one added filter drop-down, of little relevance here. I have changed the free Delete Html.ActionLink on every row to an Ajax.ActionLink, and the delete and ajax update work, but whichever container div I try and update, I always somehow get some kind of nesting in the updated page, e.g. after a delete and update, I get duplicate Home and About links from the master page inside my content.
Here is my current action link that causes what I describe above:
<%: Ajax.ActionLink("Delete", "Delete", new { id = item.InstallationDBNumber }, new AjaxOptions { UpdateTargetId = "jobList" }) %>
... and here is where jobList is located, just outside the table used for the index list:
<div style="clear: both;">
</div>
<div id="jobList" class="index-list">
<table>
<tr>
You should post your code for your Delete action method on your controller. But from the sounds of it, you are returning Return View(myModel) instead of Return PartialView("partialViewName", myModel).
Create a partial view contianing the layout information for jobList and return that from your controller action method.

Resources