MVC3 Listbox Contents to Model Values - asp.net-mvc-3

I'm using ASP.NET MVC3 and I was wondering if there's any way to create a listbox that contains the values which I would like my model to have.
Using #Html.ListBoxFor will only store the selected items into the model when the form is submitted rather than all the items in the listbox. I plan on using javascript to add items from another textbox.
Thanks

You are not clear, but are you trying to POST values back? If so, then they must be selected (i.e. active) form values in order to POST. If you use JavaScript to add options to a listbox (HTML select> then these don't post. You would need a multi-select enabled select and then flag each value you want to submit as selected.
To get values back they need to POST in some manner.

No. This has nothing to do with MVC3. This is a limitation of the HTTP model. When a form is posted, the browser only posts the selected value. It does not post the other elements of the select list.
MVC must work within the framework of the way the browsers work, and this can't be changed.

Yes, you can do this. You need a couple things to make this work though, it can be troubling.
In view:
//generate list box with
<select id="NAMEOFLISTBOX" name="NAMEOFLISTBOX" multiple="multiple">
Okay, here is the part that most people miss. The controller will only collect selected items if they are actually designated to be selected. Therefore, where your submit button is you need to include some javascript.
<input type="submit" value="DO WORK" onclick="selectLISTBOXITEMS()" />
Script:
function selectLISTBOXITEMS(){
var curList = document.getElementById("NAMEOFLISTBOX");
for (var i = 0; i < curList.length; i++) {
curList.options[i].selected = true;
}
}
In controller:
[HttpPost]
public ActionResult controllerName(List<string> NAMEOFLISTBOX)
{
foreach(string s in NAMEOFLISTBOX)
{
//do work
}
return RedirectToAction("controllerGet");
}
Not impossible, but the first time I did this it took a while to figure out why nothing was being sent.

Related

Proper way for delete function in ASP.NET MVC 4 WebGrid

I just started using WebGrid and I have been searching a proper way to delete a row.
But I don't want to use solutions which redirects the user an other window. I just want that when the user clicks delete then pop up a confirm window and if the user choose yes, delete the data and refresh the page, but with ajax.
I have found a way to do this, but I have not seen other people do it on the Internet in the same way and I want to know if it is a good practice to follow it in the future.
In the WebGrid I have the following column definition:
grid.Column(header: "", format: #<text> <button type="submit" name="Delete" value="#item.Id">Delete</button></text>)
It is in a #Ajax.Beginform(...) { ... }
In my Controller I check if a Delete button was clicked and get the Id this way:
[HttpPost]
public ActionResult Index(ManageOvertimesViewModel model, FormCollection formCollection)
{
...
if (formCollection["Delete"] != null)
{
int id = int.Parse(formCollection["Delete"]);
//Delete the data
return PartialView("IndexPartial", model);
}
...
}
When I delete something in this view other data displayed can be changed, so I need to have the posted ViewModel to recreate some DropDowns in the view and this is the reason I don't use Ajax.ActionLink to solve the delete.
So is it a good way to achieve delete?
Here you have example from View:
grid.Column("", "", canSort: false, format:#<b>#Html.ActionLink("Delete", "DeletePrizeRun", new { id = item.ID })</b>, style: "column")
Here code from controller:
public ActionResult DeletePrizeRun(int id)
{
using (var context = new ExampleDataContext())
{
var prizeRun = context.PrizeRuns.FirstOrDefault(p => p.id == id);
context.PrizeRuns.Remove(prizeRun);
context.SaveChanges();
}
}
For your solution the Grid has to be inside the the Ajax form. The ajax form will do partial updates and the grid will do (if you specify an ajax target which you must if you want to avoid page reloads, at least if you are using paging and sorting with pager / sort headers generated by WebGrid). That is where my headache with a similar solution started. The Grid started to behave strangely when sorting or paging, e.g. the controller was executed multiple times.
I ended up giving up on WebGrid and I am now using html tables with razor commands which works great and provides much better control.
I recommend not to use WebGrid for anything but the most simple demo.
Other than that I see no problem with your approach, using name / value to pass data to the controller worked for me.

Wizard in ASP.NET MVC3 and Multiple HttpPost

I am using the Wizard control described in http://afana.me/post/create-wizard-in-aspnet-mvc-3.aspx
It works great, but I need to have Multiple HttpPost within the same Controller. In my scenario, I need to add to a collection before moving to next step. In the partial view for that step. I have following set up:
#using (Html.BeginForm("AddJobExperience", "Candidate"))
{
<input type="submit" value="Add Experience" />
}
When I press the Add Experience input, it is routed to the
[HttpPost, ActionName("Index")]
public ActionResult Index(CandidateViewModel viewModel)
{
}
instead of
[HttpPost, ActionName("AddJobExperience")]
public ActionResult AddJobExperience(CandidateViewModel col)
{
}
what am I doing wrong?
It sounds like you need to break up your CandidateViewModel into separate ViewModels and your big Wizard View into separate Views so that there is one per action for each step of the wizard.
Step one they add the job experience, so have a view, viewmodel and an action for that, Step two they do whatever else and you have a separate view, viewmodel and action for that as well. etc, etc
Breaking up your CandidateViewModel into separate ViewModels will mean that you can just focus on the data required for that step, and can add the validation, then when they click submit, it posts the data to the next step.
Then, when you want to improve the UI behaviour, add some AJAX, and maybe use something like JQuery UI Tabs to make it behave more like a wizard in a desktop app.
It sounds like you still have nested forms. Don't do this, it is not valid HTML.
You have 2 options here, depending on what you are trying to achieve. If you want to post your job experiences separately one at a time, then put them in their own #using(Html.BeginForms, but don't nest them in an outer form. When a user clicks the Add Experience button, do your work on that one experience and then return a new view to the user.
If you want to post all of the job experiences at the same time, then wrap all of them in a single #using(Html.BeginForm and do not put #using(Html.BeginForm in your partial views. See another question I answered here for more info on how to post a collection of items in a single HTTP POST.
The 2nd method is what it sounds like you are trying to achieve, and for this, you should probably use AJAX to add multiple job experiences to your collection without doing a full postback. You can then do 1 HTTP POST to submit all job experiences in the collection to your wizard controller. It's not very difficult to implement a feature like this:
Given I can see the Add Experience button
When I click the Add Experience button
Then I should see a new experience partial view with input fields
And I should enter data in these fields
When I click the Add Experience button a second time
Then I should see another new experience partial view with input fields
And I should enter data in these fields
When I click the Add Experience button a third time
Then I should see a third new experience partial view with input fields
And I should enter data in these fields
When I click the Next button in the wizard
Then my controller will receive data for all 3 experiences I submitted in a single form
you need to use ActionMethodSelectorAttribute or ActionNameSelectorAttribute which allow to add new attribute on action to call different action on respective of button click
In View:
#using (Html.BeginForm())
{
<input type="submit" value="Add Experience" name="AddExperience" />
<input type="submit" value="Add Experience" name="AddJobExperience" />
}
add new class FormValueRequiredAttribute in application which extend ActionMethodSelectorAttribute class to check on which button is clicked
//controller/FormValueRequiredAttribute.cs
public class FormValueRequiredAttribute : ActionMethodSelectorAttribute
{
public string ButtonName { get; set; }
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
var req = controllerContext.RequestContext.HttpContext.Request;
return !string.IsNullOrEmpty(req.Form[this.ButtonName]);
}
}
then you should add this attribute on action to call corresponding action
In Controller
[HttpPost]
[FormValueRequired(ButtonName = "AddExperience")]
public ActionResult Index(CandidateViewModel viewModel)
{
return View();
}
[HttpPost]
[ActionName("Index")]
[FormValueRequired(ButtonName = "AddJobExperience")]
public ActionResult AddJobExperience_Index(CandidateViewModel viewModel)
{
return View();
}
Note if your Html.BeginForm method in Index.cshtml then you don't need specify ActionName attribute on Index Action, now AddJobExperience_Index act same as Index Action.

how to retrieve value of dropdown selection when form is not been submitted yet

I have following code
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.IDs, new SelectList(Model. IDs), Model.SelectedID)
}
So user selection from this combo bind to SelectedID property of the model. My understanding is that this binding happen only when form is submitted. Let’s say from the same page, I need to do an AJAX call but at this point ) Model.SelectedID does not provide any value because form hasn’t been submitted yet (although user has selected something from drop down). Any ideas how to best deal with this situation?
You can use javascript.
var selectedValue = $("#IDs").val();
bind a change event to your DD
$("#DDL_ID").change(function(){
var currVal = $(this).val();
//do ajax
});
As others have pointed you would get this value with javascript on the change of the drop down list.
I wanted to point out however, that your understanding of the overload you are using for the drop down list is incorrect. This overload will display a default option box label.
For example you could prompt the users to select select something from the list:
#Html.DropDownListFor(m => m.IDs, new SelectList(Model. IDs), "Select Something...")
If you were to post the form in your example as is, you can see the selected item come across in the form. If your view model is setup in such a fashion the model binder would take over and bind this value to your "SelectedID" property.
[HttpPost]
public string DropDown(FormCollection form)
{
var selectedItem = form["IDs"];
return selectedItem;
}

jQuery unobtrusive validation to validate part of a form

We have a ASP.NET MVC 3 application that uses unobtrusive jQuery validation. The page allows to add children objects to the model in the same go. The <form> contains a grid for the children, and some input fields for adding new children.
Simplified example with Issue as the Model and Subtasks as the children:
Issue.cshtml -> Defines the form and includes fields for the issue as well as its subtasks.
#model Issue
#using (Html.BeginForm("Create", "Issues", FormMethod.Post, new { id = "mainForm" })
{
#Html.TextBoxFor(model => model.Summary)
#Html.Partial("SubtaskFields", new Subtask())
#Html.Partial("SubtasksGrid", model.Subtasks)
}
SubtaskFields.cshtml:
#model Subtask
#Html.TextBoxFor(model => model.Summary)
<button id="add">Add</button>
SubtasksGrid.cshtml:
#model IEnumerable<Subtask>
<table>
#foreach (var subtask in Model)
{
<tr>
<td>
#subtask.Name
<input type="hidden" name="Subtasks[#subtask.Index].Name" value="#subtask.Name"/>
</td>
</tr>
}
</table>
The point is, when submitting the form, only the properties of the issue (Issue.Name, e.g.), plus the hidden fields for the children (Subtask.Name, e.g.) should be validated and submitted.
We have some javascript code that hooks on the "add" button, and adds a new subtask based on the values in the SubtaskFields.cshtml partial view. That script validates the input fields first. In order for this to work, we use the TextBoxFor etc. html helpers for the SubtaskFields.cshtml, too, rendering a dummy/default Subtask object (new Subtask()). Our javascript the uses $("#mainForm").validate().element(...) to validate the SubtaskFields before adding a new subtask.
The big problem with this approach is that the jQuery unobtrusive validation framework automatically hooks on the submit button and validates all fields within the form before submitting the form. I.e., even the subtask fields are validated. This does not make any sense. Say that the subtask name is mandatory (which means the user can only click on "add" if he has filled in a subtask name). But if the user does not click on "add", the values in the Subtask Fields don't have any meaning and can in particular be left blank. In this case, in our current setting, jQuery validation fails because a mandatory field was left blank.
How can this be solved?
This is what we've come up with:
Add an attribute to all subtask fields (which should not be validated when submitting the form), e.g. "data-val-ignore".
Set the ignore setting on the form's validator to "[data-val-ignore]"
For the add button, in order to validate the subtask fields (which are normally ignored), iterate over them, and for each field, remove the attribute, re-parse to genereate the rules, execute validation, add the attribute, parse one more time.
Ad 2:
$(document).ready(function () {
$.data($('form')[0], 'validator').settings.ignore = "[data-val-ignore]";
});
Ad 3:
$(allSubtaskFields).each(function() {
$(this).removeAttr("data-val-ignore");
$.validator.unobtrusive.parseElement(this, false);
if (!$("mainForm").validate().element($(this))) { result = false; }
$(this).attr("data-val-ignore", "true");
$.validator.unobtrusive.parseElement(this, false);
});
I would suggest moving #Html.Partial("SubtasksGrid", model.Subtasks) outside of your form, and either having it in a single separate form, or have the partial generate a form for each grid row.
This will address your validation problems with your main form, and should also permit you to simplify validation of each row in SubTasksGrid.
To validate part of the form, wrap the section or the controls you want to validate into a div with an #id or .class and do the following:
var validator = $("#myForm").validate();
var isValid = true;
$("myDivToBeValidated").find("*[data-val]").each(function (indx, elem) {
if (!validator.element(elem)) {
isValid = false;
}
});
//this part of form is valid however there might be some other invalid parts
if (isValid)
//do your action, like go to next step in a wizard or any other action
goToNextStep();
I hope it is clear, if not please leave a comment. For more info about jQuery validation plugin and element() function, check this
Looks like you are working against the MVC egine here.
I would use Editor templates and Display templates, EditorFor template for the stuff you wanna validate and post, and Display template for the stuff you dont wanna post and validate.. If you have a TextBoxFor in the display template make sure its binding property has no Required attribute, and if its a value type make it nullable.

Best method to pass value in MVC

I am still new to MVC, so sorry if this is an obvious question:
I have a page where the user can choose one of several items. When they select one, they are taken to another form to fill in their details.
What is the best way to transfer that value to the form page?
I don't want the ID of the item in the second (form) pages URL.
so it's /choose-your-item/ to /redemption/ where the user sees what was selected, and fills the form in. The item selected is displayed, and shown in a hidden form.
I guess one option is to store in a session before the redirect, but was wondering if there was another option.
I am using MVC3
Darin Dimitrov's answer would be best if you don't need to do any additional processing before displaying the /redemption/ page. If you do need to some additional processing, you're going to have to use the TempDataDictionary to pass data between actions. Values stored in the TempDataDictionary lasts for one request which allows for data to be passed between actions, as opposed to the values stored in the ViewDataDictionary which only can be passed from an action to a view. Here's an example below:
public ActionResult ChooseYourItem()
{
return View();
}
[HttpPost]
public ActionResult ChooseYourItem(string chosenItem)
{
TempData["ChosenItem"] = chosenItem;
// Do some other stuff if you need to
return RedirectToAction("Redemption");
}
public ActionResult Redemption()
{
var chosenItem = TempData["ChosenItem"];
return View(chosenItem);
}
If you don't want the selected value in the url you could use form POST. So instead of redirecting to the new page, you could POST to it:
#using (Html.BeginForm("SomeAction", "SomeController"))
{
#Html.DropDownListFor(...)
<input type="submit" value="Go to details form" />
}
To help others, this is how I resolved my issue of needing multiple buttons posting back, and wanting to pass a different Id each time.
I have a single form on the page, that posts back to my controller:
The Form:
#using (Html.BeginForm("ChooseYourItem", "Item", FormMethod.Post))
{
And the code
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChooseYourItem(string itemId)
{
TempData["ITEMID"] = itemId
return RedirectToAction("Create", "Redemption");
}
Then, inside the form, I create buttons whose name == "itemId", but has a different value each time.
For example
<strong>Item 1</strong>
<button value="123" name="itemid" id="btn1">Select</button>
<strong>Item 2</strong>
<button value="456" name="itemid" id="btn2">Select</button>

Resources