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>
Related
I created 3 Javascript functions to perform calculations and show result in 3 textboxes , When I save this page and reopen it ->it does not pull the calculated values in respective text boxes unless I move my mouse over them or click on them.
I have used window.onload method with the intention that it will run the function as the page opens.
I am using onKeyUp and onMouseMove event Listeners , maybe that is the cause of the issue. If so, which event listener should I use to perform the operation.
<div class="form-group">
#Html.Label("Admin Fee(5% of Total Amount of FNLCP Funding Used) ", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBox("AdminFeeWorkPlan", "", "{0:c}", new { #class = "form-control", id = "calculateAdminFee", #onKeyUp = "findTotal", #onMouseMove = "findTotal()" })
<script type="text/javascript">
function AdminFeee() {
var pullValue = document.getElementById('res').value || "0";
var output = (5/100) * parseFloat(pullValue);
if (!isNaN(output)) {
document.getElementById('calculateAdminFee').value = output;
}
}
window.onload = AdminFeee();
</script>
</div>
</div>
<div class="form-group">
#Html.Label("Total ", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBox("FinalTotal", "", "{0:c}", new { #readonly="readonly", #class = "form-control", id = "calculateTotal" })
<script type="text/javascript">
function findTotal() {
var one = document.getElementById('res').value || "0";
var two = document.getElementById('calculateAdminFee').value || "0";
var output2 = parseFloat(one)-parseFloat(two) ;
if (!isNaN(output2)) {
document.getElementById('calculateTotal').value = output2;
}
}
window.onload = findTotal();
</script>
</div>
</div>
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" })
I have one dropdown and one actionlink.
where this actionlink will be clicked automatically when the dropdown changes. How to do that?. below is my code, thanks.
#Html.DropDownListFor(model => model.PaymentCode, (List<SelectListItem>)ViewBag.JenisPembayarans, new { #class = "form-control" })
#Html.ActionLink(
"Detail",
"GetInsuranceCompany","ParamBlacklistPembayaran",
new { id = Model.PaymentCode }, new { #class = "ddlSubmit"})
Controller
public ActionResult GetInsuranceCompany( ParamBlacklistPembayaranViewModel model,string id)
{
LoadThirdPartyDDL(string.Empty, string.Empty, id);
return View("Create", model);
}
#Html.DropDownListFor(model => model.PaymentCode, (List<SelectListItem>)ViewBag.JenisPembayarans, new { #class = "form-control",#id="ddl" })
#Html.ActionLink("Detail",
"GetInsuranceCompany","ParamBlacklistPembayaran",
new { id = "PaymentCodeVal" }, new { #id="anchorclick",#class = "ddlSubmit"})
You should call click event on drop down change like this:
<script>
document.getElementById('ddl').onchange = function () {
var path = document.getElementById('anchorclick').href;
path = path.replace("PaymentCodeVal", document.getElementById('ddl').value);
document.getElementById("anchorclick").href=path;
document.getElementById('anchorclick').click();
};
</script>
#NOTE : You want get updated PaymentCode. you have to inject url to pass PaymentCode on change event.
Assign onchange event in new {} section where you can raise the event of the particular action link by using their id.
#Html.DropDownListFor(model => model.PaymentCode, (List<SelectListItem>)ViewBag.JenisPembayarans, new { #class = "form-control", #id = "MyId", onchange = "MyFunction()" })
<script type="text/javascript">
function MyFunction() {
//alert('Changed');
document.getElementsByClassName("ddlSubmit").click();
$('#YourLabelId').val('ReplaceWithThisValue');
}
</script>
References:
Handling onchange event in HTML.DropDownList Razor MVC
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>';
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);