MVC "Editfor" Element for a "List<string>" with the option to add new elements - asp.net-mvc

I need way to display a "List" property with the option to add new elements to the list.
So Basically
Value 1
Value 2
Button: Add new
I created an editfor template for it, where I display all the values with a foreach loop. However, each item get's an index, so when I add a new input field with javascript, the index is wrong.
Any suggestions how to achieve this.
PS: the adding of new elemens mustbe done on the client, since it is a simple form

var abccounter = 1;
$("#abcbutton").click(function () {
$('#itemlist').append('<p><input class="text-box single-line" id="listofstringname_' + abccounter + '_" name="listofstringname[' + abccounter + ']" type="text" value=""></p>');
abccounter++;
});
<p>#Html.EditorFor(model => model.listofstringname)</p>
that is what I did and it worked. the only problem I'm having (and it may be solved eventually) is I want to wrap each element with a tag but I'm not sure how. this JS just adds a new "text box element" assuming 1 as the start as my model loads 1 example by default.

Related

Svelte input binding breaks when a reactive value is a reference type?

(I'm new to Svelte so it is quite likely that I'm doing something wrong here)
UPDATE: I've added a second, slightly different REPL which may demonstrate the problem better. Try this one: https://svelte.dev/repl/ad7a65894f8440ad9081102946472544?version=3.20.1
I've encountered a problem attempting to bind a text input to a reactive value.
I'm struggling to describe the problem in words, so hopefully a reduced demo of the issue in the attached REPL will make more sense.
https://svelte.dev/repl/6c8068ed4cc048919f71d87f9d020696?version=3.20.1
The demo contains two custom <Selector> components on a page.
The first component is passed two string values ("one" and "two"):
<Selector valueOne="one" valueTwo="two"/>
Clicking the buttons next to the input field sets selectedValue to one of these values.
This, in turn, triggers the following reactive declaration to update:
$: value = selectedValue
The input field is bound to this reactive value:
<input type="text" bind:value>
So clicking the "One" button sets the input text to "one", and clicking the "Two" button sets the input field to "two".
Importantly though, you can still type anything into the input field.
The second component is passed two array values:
<Selector valueOne={[1, "one"]} valueTwo={[2, "two"]}/>
Again, clicking the buttons sets selectedValue to one of these.
However this time the reactive declaration depends on an array element:
$: value = selectedValue[1]
Everything works as before, except now you can no longer type into the input field at all.
So the question is - why does <input bind:value> behave differently for these two:
$: value = aString
vs
$: value = anArray[x]
It seems that this is only an issue when using two-way bindings.
By switching to a one-way and an on:input handler, the problem goes away:
i.e. instead of this:
<input type="text" bind:value={valX}/>
use this:
<input type="text" value={valX} on:input={e => valX = e.target.value}/>
I'm pretty sure your reactive declaration is overwriting your bound value as soon as it changes, which is with every key stroke on the input and every button press. Meaning it technically is working, you're just reverting it each time it changes. Check out this version of it that uses a watcher.
Also binding to a reactive declaration means you're never actually changing the variables with the input (which you can see in your JSON result on the first selector when you type in the input the value doesn't update only on button click).
Why not lose the reactive declaration and bind directly to the variable you want. Then use an {#if} block to switch between which version of the input you're showing based on the truthiness of index?
<script>
export let valueOne;
export let valueTwo;
export let index;
let selectedValue = index? [] : '';
let selectValue = (val) => selectedValue = val;
</script>
{#if index}
<input type="text" bind:value={selectedValue[index]} placeholder="Type anything...">
{:else}
<input type="text" bind:value={selectedValue} placeholder="Type anything...">
{/if}
<button on:click={() => selectValue(valueOne)}>One</button>
<button on:click={() => selectValue(valueTwo)}>Two</button>
<p>
<strong>Selected value:</strong> {JSON.stringify(selectedValue)}
</p>
By binding directly to the selectedValue or an index of it you have the added benefit of changing the value with the input. Here's a working example in the REPL

Why is MVC Html.RadioButton working like a checkbox instead of like a radio button?

In these code I have a strange situation:
#foreach (var subs in getSubscriptionTypes())
{
<p>#Html.RadioButton(subs.LengthMonths.ToString(), subs.Price) #subs.LengthMonths</p>
}
I get properly all of subs, but radiobuttons behave very strange - I can check all of radiobuttons, but I want to check only one (one is true, then rest is false). How to repair it?
Regards.
The first parameter of each radio button needs to be the same for them to be mutually exclusive (see this demo).
So try:
<p>#Html.RadioButton("subtype", subs.Price) #subs.LengthMonths</p>
For a better user interface, you could also add a label element using #Html.Label(...) so that the user can click on the text to select the radio:
<p>
#Html.RadioButton("subtype", subs.Price, new { id = "subtype-" + subs.Price })
#Html.Label("subtype-" + subs.Price, #subs.LengthMonths)
</p>

jquery-mobile create dynamic controlgroup and apply jquery-ui css [duplicate]

This question already has answers here:
Dynamic controlgroup and checkboxes unstyled
(6 answers)
Closed 8 years ago.
This is my code:
http://jsfiddle.net/YKvR3/34/
I would create a controlgroup with values that are in my array (name).
The problem is that when I click load button the values are added in a controlgroup but the jquery-ui styles are not loaded like in the image.
The controlgroup is not styled with jquery-ui mobile css.
$("#load").click(function(){
var name=["one","two"];
var html='<fieldset id="listPlayers" data-role="controlgroup"><legend><h1>Choose as many players as youd like to remove:</h1></legend>';
for ( var int = 0; int < 2; int++) {
html+='<input type="checkbox" name="checkbox-'+int+'a" id="checkbox-'+int+'a" class="custom" /><label for="checkbox-'+int+'a">'+name[int]+'</label>';
}
alert('<legend><h3>Choose as many players as you would like to remove:</h3></legend>'+html+'</fieldset');
$("#list").html(html+'</fieldset');
//$("#list").page();});​
What I am doing wrong?
Thanks.
$("#list").trigger('create');
From: jqm docs
if you generate new markup client-side or load in content via Ajax and inject it into a page, you can trigger the create event to handle the auto-initialization for all the plugins contained within the new markup. This can be triggered on any element (even the page div itself), saving you the task of manually initializing each plugin (listview button, select, etc.).
I do applogies if this post is too old and if my post isn't by the correct standard since it's the first time ever posting so please correct me if it's horribly bad :-]
But in case someone else comes across it, I had similar problems with how the dynamic data is displayed and I used the jsfiddles and comments above as a help, and this is what got mine to work, well somewhat near my solution, I don't have a button to load the data it's loaded automatically when the page is loaded.
Updated In my .html-file:
<div id="members"></div>
<input type="button" id="load" value="test"/>
Updated In my .js-file:
$("#load").click(function(){
var name = ["NameOne","NameTwo", "NameThree"];
var fset = '<fieldset data-role="controlgroup" id="members-ctrlgroup"><legend>This is a legend:</legend>';
var labels='';
for ( var i = 0; i < name.length; i++) {
labels += '<input type="checkbox" class="checkbox" id="c'
+ i
+ '"><label for="c'
+ i
+ '" data-iconpos="right">'
+ name[i]
+'</label>';
}
$("#members").html(fset+labels+'</fieldset>');
$("#members").trigger("create");
});
I know the "field" looks a bit weird how I divided it but I find it somewhat easier when it comes to getting the whole html-string correct in these cases.
Updated In order to have the rounded corners and have it as one controlgroup you'll have to have this approach instead. Just like the former posters showed.
Do note that the id with the checkbox and the label for= can tend to screw the output if they're not the same :-]
fiddle
In order to replace the content you should use .html(); instead of .append(), which adds the new content after the existing one.
After adding content to a jQuery Mobile Page you need to enhance the content, using for instance $("input[type='radio']").checkboxradio();
I was using
for( var i=0 ; i < html.length ; i++ ){
var spline = html[i].split("|");
inHTML = inHTML + " <input type=\"checkbox\" name=\"checkbox-"+i+"a\" id=\"checkbox-"+i+"a\" class=\"custom\" /> <label for=\"checkbox-"+i+"a\">"+ spline[0] +" , "+ spline[2] +"</label> ";
}
jq("fieldset#myFieldSet").empty();
jq("fieldset#myFieldSet" )
// Append the new rows to the body
.append( inHTML )
// Call the refresh method
.closest( "fieldset#myFieldSet" )
// Trigger if the new injected markup contain links or buttons that need to be enhanced
.trigger( "create" );

Remove Blank Entry on DropDownList in MVC

I have been looking but couldn't find any way to remove the blank item on my dropdown list. Ideally, I would like to do this without altering the model. I just want to remove the blank item from the dropdown list so that users are forced to select one (so they can't select "blank").
Note: I am using the default dropdown list that comes with the MVC framework.
Here is my code:
' controller action:
ViewBag.CompanyId = New SelectList(db.Companies, "CompanyId", "Name")
' view:
#Html.DropDownList("CompanyId", String.Empty)
#Html.ValidationMessageFor(Function(model) model.CompanyId)
How are you building the options for your dropdown?
I never have blank options.
I usually create my dropdown like this:
#Html.DropDownListFor(x=>x.Client, new SelectList(Model.Clients))
Obviously your model options will be different.
Answer: Remove String.Empty
Update on 2021: My problem was on the JS script side, I was appending an empty line within my dropdown :D
Like this:
$("#" + "YourID").append('<option></option>'); //Remove This Line
for (var i = 0; i < CountriesList.length; i++)
{
$("#" + "YourID").append('<option value="' + CountriesList[i] + '">' + CountriesList[i] + '</option>');
}
Removing the first line will get you directly the first element from your Items list :)
Happy coding everyone.

ASP.NET MVC 3 - Add/Remove from Collection Before Posting

I have a model that contains a collection, such as this:
class MyModel
{
public List<MySubModel> SubModels { get; set; }
}
In the view, I want to dynamically add/remove from this list using Javascript before submitting. Right now I have this:
$("#new-submodel").click(function () {
var i = $("#submodels").children().size();
var html = '<div>\
<label for="SubModels[' + i + '].SomeProperty">SomeProperty</label>\
<input name="SubModels[' + i + '].SomeProperty" type="textbox" />\
</div>'
$("#submodels").append(html);
});
This works, but it's ugly. And, if I want to show those labels/textboxes for the existing items, there's no clean way to do that either (without duplicating).
I feel like I should be able to use Razor helpers or something to do this. Any ideas? Help me stay DRY.
You approach may lead to unexpected errors if you when you are removing or adding the divs. For example you have 4 items, you remove the first item, then $('#submodels').children().size() will return 3, but your last inserted div has the name attribute value set SubModels[3].SomeProperty which results in a conflict. And if your posted values contain SubModels[1] but not SubModels[0] the default model binder will fail to bind the list (it will bind it as null). I had to learn this the hard way...
To eliminate the aforementioned problem (and your's) I suggest you do something like this:
$("#addBtn").click(function() {
var html = '<div class="submodel">\
<label>SomeProperty</label>\
<input type="textbox" />\
</div>'; // you can convert this to a html helper!
$("#submodels").append(html);
refreshNames(); // trigger after html is inserted
});
$(refreshNames); // trigger on document ready, so the submodels generated by the server get inserted!
function refreshNames() {
$("#submodels").find(".submodel").each(function(i) {
$(this).find("label").attr('for', 'SubModels[' + i + '].SomeProperty');
$(this).find("label").attr('input', 'SubModels[' + i + '].SomeProperty');
});
}
Then your view (or even better an EditorTemplate for the SubModel type) can also generate code like:
<div class="submodel">
#Html.LabelFor(x => x.SomeProperty);
#Html.EditorFor(x => x.SomeProperty);
</div>
It would also be possible to convert the code generation to a html helper class, and use it in the EditorTemplate and in the JavaScript code
I would recommend you going through the following blog post.

Resources