DropDown list issue in knockout js asp.net mvc 3 - asp.net-mvc-3

I have the following problem. I'm developing web application on asp.net mvc and using KnockoutJS in one of views. I have the following viewmodel
public class ExampleViewModel
{
public IEnumerable<Element> ElementsList { get; set; }
}
class Element
{
public bool Required {get;set;}
}
option Required must be set with dropdown list. I have the following block code in view
<div data-bind="foreach: ElementsList">
<select data-bind="attr: { name: 'ElementsList[' + $index() + '].Required' }, value: Required">
<option value="true">Yes</option>
<option value="false">No</option>
</select>
</div>
when I select Yes or No from drop down and submit form I have appropriate value saved in database, but when I open this view in browser after that all values in drop down list are 'Yes'. Despite the fact that when I open view and debug it I can see with Quick Watch, that each value from ElementsList has correct value of Required option ('Yes' or 'No'), all dropdown lists have a value 'Yes'.

Related

How to bind a list of objects in ASP.NET Core MVC when the posted list is smaller than original?

Using "disabled" attribute on inputs on form does not post them, which is expected and wanted. However, if you prepare a form of 3 objects in a list, disable the first and third, and submit, the 2nd object appears in post header, but does not bind to the list correctly, because it has an index [1] instead of [0].
I understand how model binding works and why it does not bind the posted object that I want, but I don't know how else to describe the problem to get specific results that would lead me to my solution. Anything I search for leads to basic post and binding examples.
List inside the model I'm using:
public IList<_Result> Results { get; set; }
Class _Result has one of the properties:
public string Value { get; set; }
I fill up the list and use it in view like so:
#for (int i = 0; i < Model.Results.Count; i++)
{
...
<td>
<input asp-for="Results[i].Value" disabled />
</td>
...
}
I have checkboxes on form, which remove (with javascript) the "disabled" attribute from the inputs and thus allow them to be posted.
When I fill up the said list with 3 _Result objects, they are shown on form and all have the "disabled" attribute. If I remove the "disabled" attribute from the first two objects and click on submit button, I receive the Results list with first 2 _Result objects, which is as expected.
However, if I remove the "disabled" attribute only from the second _Result object (the first _Result object still has "disabled" attribute), the Results list comes back empty in my Controller method.
In my Form Data Header, I see this: "Results[1].Value: Value that I want posted", which means that post occurs, but list does not bind the object due to the index.
Any idea on how I can achieve that proper binding? Also, the reason I'm using "disabled" attribute is because I'm showing many results on a single page and want to only post those that are selected.
For getting selected items, you could try checkbox with View Model instead of using jquery to control the disable property.
Change ViewModel
public class ModelBindVM
{
public IList<_ResultVM> Results { get; set; }
}
public class _ResultVM
{
public bool IsSelected { get; set; }
public string Value { get; set; }
}
Controller
[HttpGet]
public IActionResult ModelBindTest()
{
ModelBindVM model = new ModelBindVM
{
Results = new List<_ResultVM>() {
new _ResultVM{ Value = "T1" },
new _ResultVM{ Value = "T2" },
new _ResultVM{ Value = "T3" }
}
};
return View(model);
}
[HttpPost]
public IActionResult ModelBindTest(ModelBindVM modelBind)
{
return View();
}
View
<div class="row">
<div class="col-md-4">
<form asp-action="ModelBindTest">
#for (int i = 0; i < Model.Results.Count; i++)
{
<input type="checkbox" asp-for="Results[i].IsSelected" />
<label asp-for="#Model.Results[i].IsSelected">#Model.Results[i].Value</label>
<input type="hidden" asp-for="#Model.Results[i].Value" />
}
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>

Data annotation on int[]

In a ASP.NET MVC5, I'm using the chosen JS library for a multi-dropdown select. How Can I do to use Data Annotation to validate the field?
Actually I use [Required] on all fields, this multi-dropdown select too, but it isn't working.
Code:
[MinLength(1)]
public int[] fields{ get; set; }
Here is my Code in the cshtml:
#Html.ListBoxFor(x => x.fields, Model.fieldsSelect, new { data_placeholder = "pholder" })
#Html.ValidationMessageFor(model => model.fields, "", new { #class = "text-danger" })
Without the plugin I currently use (chosen) there is no validation , Here is the HTML rendered without chosen:
<div class="col-md-10">
<select data-placeholder="Enter multiple fields" data-val="true" data-val-minlength="The field fieldsmust be a string or array type with a minimum length of '1'." data-val-minlength-min="1" id="fields" multiple="multiple" name="fields">
<option value="944454">WARUYFJGHIE</option>
<option value="33033095">WEBJKHGJHGVHGAN</option>
</select>
<span class="field-validation-valid text-danger" data-valmsg-for="fields" data-valmsg-replace="true"></span>
</div>
Validation works for all my string but not this one: when I select nothing on the form, all [Required] for strings works: an error message is apparing and submit is not hitting the controller/server, but not the [MinLength(1)]... No error message and when I fill all except [MinLength(1)], the form is submitting and error occurs in the controller/server because of null.
Versions of JS validations:
jQuery Validation Plugin - v1.11.1 - 3/22/2013
jquery.validate.unobtrusive.min.js : no version (neither in the
jquery.validate.unobtrusive..js)
You can use the MinLengthAttribute
[MinLength(1)]
public int[] fields{ get; set; }
Edit
Based on additional comments, a jquery plugin is being used that hides the <select>. By default hidden fields are not validated. To include hidden fields, add the following
$.validator.setDefaults({
ignore: []
});

Add and remove textbox at runtime in mvc3

In my page there is one textbox by default and one add button beside it. I need to add the another textbox when user click Add button. And there should be two buttons Add and Remove beside newly added text box. And same process goes on i.e., user can add Textbox using Add button and remove it using remove button.
I am new to mvc 3 so i am confused how to proceed. Is there any way like placeholder in asp.net so that we can add control at runtime.
Any suggestion and idea will be helpful to me
MVC is a very "hands-off" framework compared to Web Forms, so you're free to add the new textboxes how you like. Note that "controls" don't exist in MVC.
Here's how I'd do it:
Model:
class MyModel {
public Boolean AddNewTextBox { get; set; }
public List<String> MultipleTextBoxes { get; set; } // this stores the values of the textboxes.
}
View (I prefer the Web Forms view engine, I'm not a fan of Razor):
<% for(int i=0;i<Model.MultipleTextBoxes.Count;i++) { %>
<%= Html.TextBoxFor( m => m.MultipleTextBoxes[i] ) /* this might look like magic to you... */ %>
<% } %>
<button type="submit" name="AddNewTextbox" value="true">Add New Textbox</button>
<button type="submit">Submit form</button>
Controller:
[HttpPost]
public ActionResult MyAction(MyModel model) {
if( model.AddNewTextBox ) model.MultipleTextBoxes.Add("Yet another");
else if( ModelState.IsValid ) {
// your regular processing
}
}
You can also add more textboxes with Javascript and it work perfectly fine. All that matters is the HTML input elements. There's no cryptic viewstate. MVC is stateless.
Note that because I used <button type="submit"> my example will not work reliably in Internet Explorer 6-8 (sucks, I know), but you can replace them with <input type="submit"> with no ill-effects.
This requires some Javascript/JQuery... The following is a sketch only, but will hopefully be useful as a general approach.
The remove button
You want to render a button that can target its own container for removal. To do that, use some markup like this:
<div class="item-container">
<input type="button" onclick="removeItem(this)" />
</div>
And the Javascript for removeItem:
<script>
function removeItem(element) {
// get the parent element with class "item-container" and remove it from the DOM
$(element).find(".item-container").remove();
}
</script>
The add button
You could either use a partial view with Ajax, or use straight Javascript; which one is best likely depends on whether you need a round-trip to the server to create a new item. Let's say you need to go the the server to generate a new ID or something.
First, create a partial view and corresponding controller action; this should contain the remove button as above, as well as the text box and add button.
Now, create an Ajax form on your main page that gets invoked when you click Add:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
#using (Ajax.BeginForm("New", new AjaxOptions() { UpdateTargetId="ajaxTarget", HttpMethod = "GET" })) {
<input type='submit' value='Add New' />
}
<div id="ajaxTarget"></div>
This code fetches your partial view (from the action New in the current controller) and adds the result to the ajaxTarget element.
Note The Ajax form requires Unobtrusive Ajax, which you can install via Nuget: Install-Package JQuery.Ajax.Unobtrusive.

ASP.NET MVC3 Validation of nested view model object fields

I have a view model that looks like this:
public class VenueIndexViewModel : BaseViewModel
{
public VenueAddViewModel Venue;
...
}
public class VenueAddViewModel
{
...
[Required(ErrorMessage = "This field is required")]
public string State { get; set; }
...
}
In my view, I'm rendering a form with with a drop down list for this property like so:
using (var form = Html.BeginForm())
{
...
#Html.DropDownListFor(x => x.Venue.State, Model.GetStates())
#Html.ValidationMessageFor(x => x.Venue.State)
...
}
This works, but the problem is that the the Required attribute on the view model appears to be ignored. If I look at the HTML, the data-val-* attributes are missing as well.
<select id="Venue_State" name="Venue.State">...</select>
However, if I change the rendering to a textbox...
using (var form = Html.BeginForm())
{
...
#Html.TextBoxFor(x => x.Venue.State)
#Html.ValidationMessageFor(x => x.Venue.State)
...
}
I see the expected data-val-* attributes and the validation works:
<input data-val="true"
data-val-required="This field is required"
id="Venue_State" name="Venue.State" type="text" value="">
I should note that I have other view models elsewhere that use DropDownListFor with a flat view model (no nested objects) and the validation works fine there, so I'm thinking I've hit a bug in the MVC validation handling for drop down lists when using a nested view model. Can anyone confirm / advise?
As far as I know you can't have client side validation on nested objects. And a quick google search seems to confirm that.
http://forums.asp.net/t/1737269.aspx/1

ASP.NET MVC2 validation not working with drop down list in IE <8

I have a form with a dropdownlist rendered using Html.DropDownListFor(...). The view model field that corresponds with the dropdown list has a [Required(...)] attribute attached to it. This works fine on my local machine, but as soon as I publish to our development server, the drop down lists keep displaying the required error message, even when a value is selected in the list. This only happens in IE - Firefox submits just fine.
Any thoughts?
Relevant code
View:
<ol class="form">
<li>
<%= Html.LabelFor(x => x.ContactTitle) %>
<%= Html.DropDownListFor(x=>x.ContactTitle, Model.GetTitleOptions()) %>
<%= Html.ValidationMessageFor(x => x.ContactTitle) %>
</li>
<!-- more fields... -->
</ol>
View Model:
[Required(ErrorMessage = "Title is required")]
[DisplayName("Title")]
public string ContactTitle { get; set; }
// ...
public SelectList GetTitleOptions()
{
return new SelectList(new string[]
{
"","Dr.", "Mr.", "Ms.", "Mrs.", "Miss"
});
}
It's all pretty basic stuff... I'm at a loss.
Edit: Just discovered this bug is limited to IE 8 compatibility view (and maybe prior versions). IE 8 in standards mode works as expected...
Chalk this one up to stupidity. The code in the example produces output similar to the following:
<select>
<option></option>
<option>Dr.</option>
<option>Mr.</option>
<option>Ms.</option>
<option>Mrs.</option>
<option>Miss</option>
</select>
And the relevant MVC validation function (when a RequiredAttribute is applied to a property that corresponds to a drop down list) is:
Sys.Mvc.RequiredValidator._validateSelectInput = function Sys_Mvc_RequiredValidator$_validateSelectInput(optionElements) {
/// <param name="optionElements" type="DOMElementCollection">
/// </param>
/// <returns type="Object"></returns>
for (var i = 0; i < optionElements.length; i++) {
var element = optionElements[i];
if (element.selected) {
if (!Sys.Mvc._validationUtil.stringIsNullOrEmpty(element.value)) {
return true;
}
}
}
return false;
}
Notice the function checks element.value. In the case of the html above, the value attribute is empty because there is no value attribute on the option elements. Therefore, the validation function returns false and the error occurs. This only appears to happen in IE <8, presumably because other browsers by default assign an option element's text to the value attribute if none is specified.
The solution was to modify the way I was returning the select list items from which the drop down list was built like so:
public IEnumerable<SelectListItem> GetTitleOptions()
{
return BuildSelectListItems(new string[]
{
"","Dr.", "Mr.", "Ms.", "Mrs.", "Miss"
});
}
private List<SelectListItem> BuildSelectListItems(IEnumerable<string> values) {
return (from v in values
select new SelectListItem()
{
Text = v,
Value = v
}).ToList();
}
This results in the much more predictable HTML output:
<select>
<option value=""></option>
<option value="Dr.">Dr.</option>
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss">Miss</option>
</select>
which of course the function validates properly.

Resources