Add Actors to a list for DVD Library - javascript

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);

Related

result calculated by Javascript function and displayed in another textbox ->does not instantly come up when I open the web page

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>

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" })

How to click ActionLink automatically when the dropdown is changes?

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

Add controls dynamically to an HTML table using Razor

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>';

I have a requirement which I need to display price based on drop down selection

I have a requirement which I need to display price based on drop down selection. and that price comes from same db, when I click one Test from dropdown then respected price of that test should display in textbox.The value is binding in textbox after selecting option from dropdown also it is displaying after taking span but not displaying on textbox, please tell me solution because i want to display it only on textbox .
here is Error Image
Model class
public partial class TwoDDiagnostic
{
public int TwoD_ID { get; set; }
public string TwoDDiagnostic_Name { get; set; }
public string TwoD_Price { get; set; }
public Nullable<System.DateTime> TwoD_Date { get; set; }
public Nullable<int> centr_Id { get; set; }
}
Controller
IEnumerable<SelectListItem> selectList2D = from twod in db.TwoDDiagnostics
where twod.centr_Id == Id
select new SelectListItem()
{
Text = twod.TwoDDiagnostic_Name,
Value = twod.TwoDDiagnostic_Name
};
var lasttwoD = db.TwoDDiagnostics.Where(x => x.centr_Id == Id).OrderByDescending(c => c.TwoD_ID).Take(1).FirstOrDefault();
if (lasttwoD == null)
{
ViewBag.twoDID = new SelectList(selectList2D, "Value", "Text");
model.ViewModel_TwoDDiagnostic = null;
return View(model);
}
string twodname = (from sub in db.TwoDDiagnostics where sub.TwoD_ID == lasttwoD.TwoD_ID select sub.TwoDDiagnostic_Name).First();
ViewBag.twoDID = new SelectList(selectList2D, "Value", "Text", twodname);
View
<div class="form-inline">
<label for="inputEmail1" class=" col-lg-2 col-sm-4 control-label">2D Diagnostic Services</label>
<div class="col-lg-5">
#Html.DropDownListFor(model => model.PTwoDDiagnostic_name, (SelectList)ViewBag.twoDID, "- Select 2D Diagnostics -", new { #class = "form-control ", #id = "twopID", #onchange = "fill()" })
</div>
<div class="col-lg-3">
#*<span class="form-control" id="twoprice"></span>*#
#Html.TextBoxFor(model => model.PTwoDDiagnostic_price, new { #class = "form-control ", #id = "twoprice" , #onchange = "fill()"})
</div>
</div>
here is json method
public JsonResult GetTwoDPrice()
{
AllViewModel model = new AllViewModel();
Session["Two_D"] = model.TwoD_ID;
var id = (int)Session["Two_D"];
if (!string.IsNullOrEmpty(Session["Two_D"].ToString()))
{
//int Id = (int)Session["Two_D"];
var Record = (from patient in db.TwoDDiagnostics
where patient.TwoD_ID == id
select new
{
TwoD_ID = patient.TwoD_ID,
TwoD_Price = patient.TwoD_Price
}).FirstOrDefault();
return Json(Record, JsonRequestBehavior.AllowGet);
}
return Json("", JsonRequestBehavior.AllowGet);
}
here is a script
<script type="text/javascript">
$("#twopID").on('change', function (event) {
$.ajax({
url: "#Url.Action("GetTwoDPrice", "Center")",
type: "Get",
success: function (data) {
debugger;
console.log(data.TwoD_Price);
$('#twoprice').text(data.TwoD_Price);
}
});
});
</script>
You need to use the jquery val() method to set the Value for the TextBox. If you use text() method, it sets the innerText of the input element (in between the <input> and </input> HTML tags) which is applicable only for HTML Elements like span, label, h, div, etc.
$('#twoprice').val(data.TwoD_Price);

Categories

Resources