Add controls dynamically to an HTML table using Razor - javascript

I'm trying to assign a select to a string variable. Using:
var h1 = '<td>#Html.DropDownList("idControlClass", new SelectList(Model.FooList), htmlAttributes: new { #class = "form-control" })</td>';
The outcome is "Uncaught SyntaxError: Invalid or unexpected token" since the snippet of code results in a string with line breaks after the closing option tags.
Is there a way of assigning a the select generated from the code above to a variable without line breaks? Or some other way of achieving the same result?

Your passing SelectList but it expecting List<SelectListItem>
try this
#{
List<SelectListItem> lstControlClass = new List<SelectListItem>();
foreach (var item in Model.FooList)
{
lstControlClass.Add(new SelectListItem() { Text = item.Id , Value = item.Name })
}
}
var h1 = '<td>#Html.DropDownList("idControlClass", lstControlClass, htmlAttributes: new { #class = "form-control" })</td>';
Or You need to set key where's is Text and Value
var h1 = '<td>#Html.DropDownList("idControlClass", new SelectList(Model.FooList, "Id","Name"), htmlAttributes: new { #class = "form-control" })</td>';

Related

Read a date from textbox1 and show next date in textBox2

Below is my code, please advise where I am making a mistake . Textbox2 does not show anything.
code for textbox1:-
<td>
#Html.EditorFor(model => model.DailyRegister.Date, new { htmlAttributes = new { #class = "form-control", required = "required", #id = "date1",#onchange="addDates2()" } })
#Html.ValidationMessageFor(model => model.DailyRegister.Date, "", new { #class = "text-danger" })
<script>
function addDates() {
document.getElementById("date1").value = document.getElementById("StartDate").value;
}
</script>
</td>
code for textBox2
<td>
#Html.EditorFor(model => model.DailyRegister.Date, new { htmlAttributes = new { #class = "form-control", required = "required", #id = "date2" } })
#Html.ValidationMessageFor(model => model.DailyRegister.Date, "", new { #class = "text-danger" })
<script>
function addDates2() {
var prev=document.getElementById("date1").value
var neww= prev.setDate(prev.getDate() + 1);
document.getElementById("date2").value = neww;
}
</script>
</td>
After doing my research , below is the answer to this scenario with details in comments.
<script>
function nextDate3() {
//Date object us work with dates. By default js will use browser's time zone and display a date as a full text string.
var prev = new Date(document.getElementById("date2").value)
var nextDay = new Date(prev);
nextDay.setDate(prev.getDate() + 1);
// SetDate() sets the day of the specified DATE and getDate() returns the day from the specified DATE
document.getElementById("date3").value = nextDay.toDateString();
//toDateString() method returns only date portion of a Date object as a String
}
</script>

Why does this DropDownListFor element not selecting the model value?

The value needed to be selected is confirmed to be exist in the list but does not give it as selected.
_ApproverPartial.cshtml
#Html.DropDownListFor(model => model.UserId,
new SelectList(TempData["UserList"] as List<UserModel>, "Id", "DisplayName"),
"Please Select", new { #class = "form-control mt-2",
id = "UserId-" + Model.BusinessSurveyId + "-" + Model.SectionId })
Using JavaScript to make the component select the value works as intended.
But cannot make work directly with the dropdownlistfor helper?
The following code demonstrates how to create a collection of SelectListItem objects used to populate the drop-down list:
#{
var model = TempData["UserList"] as List<UserModel>;
#Html.DropDownListFor(m => model.GetEnumerator().Current,
model.Select(d =>
{
return new SelectListItem() { Text = "UserId-" + d.BusinessSurveyId + "-" + d.SectionId, Value = d.UserId };
}),
null, new { #class = "form-control mt-2" })
}
It is reasonable to use the strongly typed view.In a action method:
List<UserModel> model = /* populate the data model*/;
return View(model);
In the view:
#model IList<UserModel>
#Html.DropDownListFor(m => Model.GetEnumerator().Current,
Model.Select(d =>
{
return new SelectListItem() { Text = "UserId-" + d.BusinessSurveyId + "-" + d.SectionId, Value = d.UserId.ToString() };
}),
null, new { #class = "form-control mt-2" })

Add Actors to a list for DVD Library

So I have a DVD object which contains a list of actors. I have an add view (everything else adds fine) but I'm stuck on trying to get the actors to add to the list on the DVD. I attempted to integrate JavaScript into it to create new text boxes for each actor, but it isn't actually saving more than the first one. Any advice / suggestions?
Here is the code in the view for the actor list:
<div id="actorsContainer">
<div class="form-group">
#Html.LabelFor(model => model.dvd.ActorList, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.dvd.ActorList, new { htmlAttributes = new { #class = "form-control", id = "actors", name = "actors[]" } })
<input type="button" class="btn-sm btn-default col-md-2" id="addActor" value="+" />
#Html.ValidationMessageFor(model => model.dvd.ActorList, "", new { #class = "text-danger" })
</div>
</div>
</div>
And here is what I used currently for the JavaScript:
<script>
document.getElementById("addActor").onclick = function () {
var div = document.getElementById("actorsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "actors[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
Update:
Here is the code I have for the controller as well. Maybe this have something to do with it? Also only one addActor button exists, but hoping to add a textbox each time it is clicked to add multiple actors.
[HttpGet]
public ActionResult AddDVD()
{
DVDListVM vm = new DVDListVM();
return View(vm);
}
[HttpPost]
public ActionResult AddDVD(DVDListVM model)
{
if (ModelState.IsValid)
{
DVD newDVD = new DVD();
newDVD.Title = model.dvd.Title;
newDVD.ReleaseYear = model.dvd.ReleaseYear;
newDVD.DirectorName = model.dvd.DirectorName;
newDVD.Studio = model.dvd.Studio;
newDVD.MPAARating = model.dvd.MPAARating;
newDVD.ActorList = model.dvd.ActorList;
newDVD.UserNotes = model.dvd.UserNotes;
newDVD.UserRating = model.dvd.UserRating;
_dvdManager.AddDVD(newDVD);
return RedirectToAction("Collection");
}
else
{
return View(model);
}
}
If ActorList is a collection, you need to create an input for every record in the collection like this:
#for (int i = 0; i < model.dvd.ActorList.Count; i++)
{
#Html.TextBoxFor(model => model.dvd.ActorList[i], new { htmlAttributes = new { #class = "form-control"} })
}
I do not assign id and name attributes since razor generates values for this attributes automatically.
If you want to create inputs dynamically, you need to check out html rendered by razor and how it handles indexes for collections. I use asp.net mvc core and that's how email input which is part of a collection looks in html:
<input name="EmailAddresses[1].EmailAddress" class="form-control emailInputAddress" id="EmailAddresses_1__EmailAddress" type="email" value="">
To create inputs dynamically I get element index, increment it, and then create a copy of element with new index.
var newEmailInput = $(".emailInput:last").clone(true)[0].outerHTML;
//get index generated by razor and increment it
var newEmailInputIndex = newEmailInput.match(/(\[([^\]]+)\])/i)[0].match(/\d+/i)[0];
newEmailInputIndex++;
newEmailInput = newEmailInput.replace(/(\[([^\]]+)\])/ig, "[" + newEmailInputIndex + "]")
.replace(/(_([^_]+)__)/ig, "_" + newEmailInputIndex + "__");
$(this.lastEmailInput).after(newEmailInput);

set DropDownListFor with value ng-model instead SelectedIndex

I have DropDownListFor in MVC view, with this line:
#Html.DropDownListFor(m => m.UserOffice, Enumerable.Empty<SelectListItem>(), new { #class = "form-control", data_ng_model = "OfficeID", data_ng_options = "I.Id as I.Name for I in OfficeList", #id = "UserOffice" })
I need to store in "m.UserOffice" the "data_ng_model" value instead Selected index.
how can I do it ?

Get the name of the textbox in Partial

#model DateTime?
<script type="text/javascript">
$(document).ready(function () {
var NameField = $(".pdate");
alert(NameField.attr("name"));
var objCal1 = new AMIB.persianCalendar(NameField);
});
</script>
#Html.TextBox("", Model, new { #class = "pdate" })
#Html.Hidden("", Model)
no display messagebox!!!!
and set under line
no display messagebox!!!!
and set under line
no display messagebox!!!!
and set under line
Your text box has no name. Give name like following
#Html.TextBox("aName", Model, new { #class = "pdate" })

Categories

Resources