Asp.Net MVC Strongly Typed Collections. EditorFor not appending generated prefix - asp.net-mvc-3

I'm using this tutorial at the moment.
(I believe my issue is related to strongly typed collections... by what I've been seeing on the internet, but I could be wrong)
Please bear with me. :)
I've been having this issue which I asked in another question, the answer seemed fine, but after tinkering with the code a bit more I realized that the issue is that the fields that make use of my custom partial view, don't get a prefix added to them like the fields that use a TextBoxFor html helper, for example. EG. When I click on add a new item, it adds it, but with the same ID as an item that's been added before, then my Javascript fails because there's two items with the same id.
Some code to try and clarify the issue
Partial View
#model Portal.ViewModels.Micros
#using Portal.Helpers
<div class="editorRow" style="padding-left:5px">
#using (Html.BeginCollectionItem("micros"))
{
#Html.EditorFor(model => model.Lab_T_ID)
#Html.EditorFor(model => model.Lab_SD_ID)
#Html.TextBoxFor(model => model.Result)
<input type="button" class="deleteRow" title="Delete" value="Delete" />
}
</div>
The TextBoxFor (Result) gets rendered as
<input id="micros_5e14bae5-df1b-4c42-9e96-573a8e52f8b2__Result" name="micros[5e14bae5-df1b-4c42-9e96-573a8e52f8b2].Result" type="text" value="">
Editor For get rendered as
<select id="Lab_SD_ID" multiple="multiple" style="width: 300px; display: none; " >
<option value="5" selected="selected">Taken at Packing 1</option>
<option value="6">Taken at Packing 2</option>
<option value="7">Taken at Packing 3</option>
</select>
<button type="button" class="ui-multiselect ui-widget ui-state-default ui-corner-all" aria-haspopup="true" tabindex="0" style="width: 300px; ">
<span class="ui-icon ui-icon-triangle-2-n-s"></span><span>Taken at Packing (Winc 4/5-25d)</span></button>
I can include more code if its needed, there is a helper class as well (BeginCollectionItem), that I used which is located in the demo project in the tutorial as well.
I basically need to find out how "micros[5e14bae5-df1b-4c42-9e96-573a8e52f8b2]." gets appended to the input boxes as far as I can see, but have been stumped by it so far :/

The reason this works with TextBoxFor and not your custom EditorFor is because the TextBoxFor helper respects the template navigational context whereas in your editor template you have simply hardcoded a <select> element that doesn't even have a name. I would recommend you to use HTML helpers when generating input fields:
So replace your hardcoded select in the custom template with:
#model int?
#{
var values = ViewData.ModelMetadata.AdditionalValues;
}
<span>
#Html.DropDownList(
"",
Enumerable.Empty<SelectListItem>(),
new {
multiple = "multiple",
style = "width:" + values["comboboxWidth"] + "px",
data_url = Url.Action((string)values["action"], (string)values["controller"]),
data_noneselectedtext = values["noneSelectedText"],
data_value = values["id"],
data_text = values["description"]
}
)
</span>

Related

Need to show the down arrow in dropdown list in ASP.NET Core MVC

Working on an ASP.NET Core 6 MVC app. I am created a dropdown using the select asp-for tag helper. But I am not seeing a dropdown down arrow. Also I want to set the top or particular value selected by default.
Below is code and image of a dropdown
<div class="col-sm-3">
<select name="products" class="form-control "
asp-items="#(new SelectList(ViewBag.ddaircraft,"id","name"))">
</select>
</div>
Action Method code for ViewBag:
Public IActionResult Index()
{
var countries= _countries.getCountries();
//add an country item on the top of list.
countries.Insert(0, new Aircraft { Registration="0"});
//i used the country.name for value and item
var ddforAircraft = from country in countries
select new { id = country.name, name=country.name=="0"?"Item List":country.name };
// ddforAircraft.Append(new { id = "0", name = "" });
ViewBag.ddaircraft = ddforAircraft;
return View()
}
I found the answer, after Tiny Wang pointed me to the direction which really helped me to search the answer.
In order to see the dropdown down arrow I added a css class "form-select" without removing anything and I started to see the down arrow
<div class="col-sm-3">
<select name="products" class="form-control form-select-sm form-select " asp-items="#(new SelectList(ViewBag.ddaircraft,"id","name"))">
</select>
</div>
Missing dropdown arrow resulted from the class form-control, I test in my side and I found the arrow can be seen by default until I add class="form-control " to my code:
removing this 2 options then the arrow appeared again, so it proved to relate to the class, you may need to update the style:
Then I use Jquery to change the default selected option when page is loading in my code, my selector has Id Country, then change the value(ListItem.Value):
<select asp-for="Country" asp-items="#(new SelectList(Model.Countries, nameof(ListItem.Value), nameof(ListItem.Text)))">
<option>Please select one</option>
</select>
#section Scripts{
<script>
$("#Country").val('Canada')
</script>
}

Get DropDownList value into POST method

I am working on this ASP.NET Core MVC where I have this DropDownLisit which gets its values from Controller using ViewBag.DishTypes. However, upon submitting the form, the POST method is not getting the value of the option selected in the DropDownList. The code snippets are as follows:
Controller: GET Method
var allDishTypes = _context.DishType
.ToList()
.Select(dt => new SelectListItem { Value = dt.DishTypeId.ToString(), Text = dt.DishTypeName.ToString() }).ToList();
ViewBag.DishTypes = allDishTypes;
return View();
View
<form asp-controller="Home" asp-action="AddMenuItems">
<div class="row">
<label class="my-1 mr-2" for="inlineFormCustomSelectPref">Dish Type</label>
<div class="input-group">
<div class="fg-line form-chose">
<label asp-for="DishTypeId" class="fg-labels" for="DishTypeId">Dish Type</label>
<select asp-for="DishTypeId" asp-items="ViewBag.DishTypes" class="form-control chosen" data-placeholder="Choose Dish Type" required name="dishtype" id="dishtype">
<option value=""></option>
</select>
</div>
</div>
....
Controller: POST Method
[HttpPost]
public IActionResult AddMenuItems([Bind("DishTypeId, DishName, Cost")] Dishes dishesObj)
{
....
}
the POST method is not getting the value of the option selected in the DropDownList
Note that you specified a name=dishtype within your code. By this way, the field name is
always the same as this name attribute, i.e, dishtype instead of DishTypeId, which will not be recognized by ASP.NET Core by default.
To fix that issue, simply remove that attribute such that it uses asp-for to generate the name attribute automatically:
<select asp-for="DishTypeId" asp-items="ViewBag.DishTypes"
class="form-control chosen" data-placeholder="Choose Dish Type" required
name="dishtype" id="dishtype"
>
<option value=""></option>
</select>

What is the proper way to edit items in a listview when using Kendo UI Mobile & MVVM?

What is the proper way to edit items in a listview when using Kendo UI Mobile & MVVM?
I don't get the expected results when using the following:
HTML
<div id="itemsView"
data-role="view"
data-model="vm">
<ul data-role="listview" data-bind="source: items"
data-template="itemsTemplate">
</ul>
<script id="itemsTemplate" type="text/x-kendo-template">
<li>
#=Name#
</li>
</script>
<input type="text" data-bind="value: newValue" />
<button data-role="button" data-bind="click: update">update</button>
</div>​
JavaScript
var vm = kendo.observable({
items: [{
Name: "Item1"}],
newValue: '',
update: function(e) {
var item = this.get("items")[0];
item.set("Name", this.get("newValue"));
//adding the follwoing line makes it work as expected
kendo.bind($('#itemsView'), vm);
}
});
kendoApp = new kendo.mobile.Application(document.body, {
transition: "slide"});​
I expect the listview to reflect the change to the Name property of that item. Instead, a new item is added to the listview. Examining the array reveals that there is no additional item, and that the change was made. (re)Binding the view to the view-model updates the list to reflect the change. Re-Binding after a change like this doesn't seem to make any sense.
Here is the jsfiddle:
http://jsfiddle.net/5aCYp/2/
Not sure if I understand your question properly: but this is how I did something similar with Kendo Web UI, I expect mobile is not so different from Web UI from API perspective.
$element.kendoListView({
dataSource: list,
template: idt,
editTemplate: iet,
autoBind: true
});
The way I bind the listview is different, but I guess you can get similar results with your method as well.
I pass two templates to the list view, one for displaying and one for editing.
Display template contains a button (or any element) with css class k-edit to which kendo will automatically bind the listview edit action.
display template:
<div class="item">
# if (city) { #
#: city #<br />
# } #
# if (postCode) { #
#: postCode #<br />
# } #
<div class="btn">
<span class="k-icon k-edit"></span>Edit
<span class="k-icon k-delete"></span>Delete
</div>
</div>
Edit template
<div class="item editable">
<div>City</div>
<div>
<input type="text" data-bind="value: city" name="city" required="required" validationmessage="*" />
<span data-for="city" class="k-invalid-msg"></span>
</div>
<div>Post Code</div>
<div>
<input type="text" data-bind="value: postCode" name="postCode" required="required" validationmessage="*" />
<span data-for="postCode" class="k-invalid-msg"></span>
</div>
<div class="btn">
<span class="k-icon k-update"></span>Save
<span class="k-icon k-cancel"></span>Cancel
</div>
</div>
Clicking that element will put the current element on edit mode using the editTemplate.
Then on the editTemplate there is another button with k-update class, again to which kendo will automatically bind and call the save method on the data source.
Hopefully this will give you more ideas on how to solve your issue.
The problem was caused by the <li> in the template. The widget already supplies the <li> so the additional <li> messes up the rendering. This question was answered by Petyo in the kendo ui forums

Loading a codeigniter view with a form from inside another view

Using codeigniter, I've been trying to load a view inside of a foreach loop, as follows:
$posts = $this->postslibrary->getAllPosts();
foreach($posts as $post){
$home['content'][$i] = $this->load->view('post', $post['data'], true);
$i++;
}
$this->load->view('head');
$this->load->view('home', $home);
$this->load->view('footer');
Each of those post views looks a little like this:
<div class="postnum<?=$post_num?>">
<p>Posted by: <?=$poster_name?></p>
<p>Reply to: <?=$poster_name?></p>
<form>
<input type='text' />
<input type='submit' />
</form>
</div>
And they're being loaded mostly successfully in the 'home' view (which is below for thoroughness).
<div ="posts">
<?php
for($i=0;$i<$count;$i++)
{
echo($content[$i]);
}
?>
<div class="clear"></div>
<a href='/posts/browse/'>Load more items</a>
</div>
But my output ends up looking like:
<div class='posts'>
<div class='postnum1'>
<p>Posted By: Jim</p>
<p>Reply to Jim</p>
<input type='text' />
<input type='submit' />
</div>
</div>
Why are my form tags not coming through?
Check if you already have a form around the current form. Chrome is one of the browsers which doesn't accept this and removes the second form. Using a form in a form is bad practice and I suggest you find a different solution to do the form handling.
Slightly left-of-field answer, but have a look at CodeIgniter Form Generator. I've used it a couple of times and it seems pretty good for generating forms from an array. It's a bit tricky to get your head around it to begin with, but it works well once you've gotten into it.
The basic idea is that you implement a form controller from your ordinary controller, and then just output it in your view file. It might be a more elegant (and sustainable) solution to what you're trying.

MVC3 Razor Partial view render does not include data- validation attributes

I have a farily straight forward form that renders personal data as a partial view in the center of the form. I can not get client side validation to work on this form.
I started chasing down the generate html and came up with the same model field rendered on a standard form and a partial view.
I noticed that the input elements are correctly populated on the first call, #html.partial, the following only happens when the partialview is reloaded via an ajax request.
First the header of my partial view, this is within a Ajax.BeginForm on the main page.
#model MvcMPAPool.ViewModels.EventRegistration
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function ()
{
$(".phoneMask").mask("(999) 999-9999");
});
</script>
#{
var nPhn = 0;
var dTotal = 0.0D;
var ajaxOpts = new AjaxOptions{ HttpMethod="Post", UpdateTargetId="idRegistrationSummary", OnSuccess="PostOnSuccess" };
Html.EnableClientValidation( true );
Html.EnableUnobtrusiveJavaScript( true );
}
Here is the razor markup from the partial view:
#Html.ValidationMessageFor(model=>Model.Player.Person.Addresses[0].PostalCode)
<table>
<tr>
<td style="width:200px;">City*</td>
<td>State</td>
<td>Zip/Postal Code</td>
</tr>
<tr>
<td>#Html.TextBoxFor(p=>Model.Player.Person.Addresses[0].CityName, new { style="width:200px;", maxlength=50 })</td>
<td>
#Html.DropDownListFor(p=> Model.Player.Person.Addresses[0].StateCode
, MPAUtils.GetStateList(Model.Player.Person.Addresses[0].StateCode))</td>
<td>
<div class="editor-field">
#Html.TextBoxFor(p=>Model.Player.Person.Addresses[0].PostalCode, new { style="width:80px;", maxlength=10 })
</div>
</td>
</tr>
</table>
Here is the rendered field from the partial view:
<td>
<div class="editor-field">
<input id="Player_Person_Addresses_0__PostalCode" maxlength="10" name="Player.Person.Addresses[0].PostalCode" style="width:80px;" type="text" value="" />
</div>
</td>
Here is the same model field rendered in a standard view:
<div class="editor-field">
<input data-val="true" data-val-length="The field Postal/Zip Code must be a string with a maximum length of 10." data-val-length-max="10" data-val-required="Postal or Zip code must be provided!" id="Person_Addresses_0__PostalCode" maxlength="10" name="Person.Addresses[0].PostalCode" title="Postal/Zip Code is required" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Person.Addresses[0].PostalCode" data-valmsg-replace="true"></span>
</div>
Notice that the partial view rendering has no data-val-xxx attributes on the input element.
Is this correct? I do not see how the client side validation could work without these attributes, or am I missing something basic here?
In order to create the unobtrusive validation attributes, a FormContext must exist. Add the following at the top of your partial view:
if (this.ViewContext.FormContext == null)
{
this.ViewContext.FormContext = new FormContext();
}
If you want the data validation tags to be there, you need to be in a FormContext. Hence, if you're dynamically generating parts of your form, you need to include the following line in your partial view:
#{ if(ViewContext.FormContext == null) {ViewContext.FormContext = new FormContext(); }}
You then need to make sure you dynamically rebind your unobtrusive validation each time you add/remove items:
$("#form").removeData("validator");
$("#form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#form");

Resources