#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" })
Related
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);
So, I want to change my checkbox, that has checked and unchecked state to radio buttons that say, Yes (checked) or No (unchecked).
Here's what I did for the checkbox:
In my view:
#Html.CheckBoxUi("PerpendicularCheckbox",#H.GetString("IsPerpendicular"), null, new { style = "margin-right:10px", #class = "type-style-paragraph" })
js:
$('input:checkbox[name=PerpendicularCheckbox]').on({
"change": function () {
if (getUpdate()) {
var $this = $(this);
if (($this).is(':checked'))
$("ul li button").click();
}
}
});
if (!Perpendicular) {
$("#PerpendicularCheckbox").prop("checked", false);
}
else {
$("#PerpendicularCheckbox").prop("checked", true);
}
I was wondering what would I need to change it to radio buttons, yes and no options, using html extension in asp.net mvc?
EDIT:
My loosy attempt at radio buttons:
#Html.RadioButtonForUi("PerpendicularCheckbox",#H.GetString("IsPerpendicular"), null, new { style = "margin-right:10px", #class = "type-style-paragraph" })
$('input:radio[name=PerpendicularCheckbox]').on({
"change": function () {
if (getUpdate()) {
var $this = $(this);
if (($this).is(':checked'))
$("ul li button").click();
}
}
});
RadioButtonForUi :
public static MvcHtmlString RadioButtonForUi<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
string name,
bool IsEnable,
bool IsChecked,
object onchange = null,
string className = "",
bool isRequreid = true
) {etc.....}
Here is a tested sample:
<div class="form-group">
#Html.LabelFor(model => model.SaleOfPropertyPurchase, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.RadioButtonFor(model => model.SaleOfPropertyPurchase, true, new { id = "SaleOfPropertyPurchase-true" }) Yes
#Html.RadioButtonFor(model => model.SaleOfPropertyPurchase, false, new { id = "SaleOfPropertyPurchase-false" }) No
#Html.ValidationMessageFor(model => model.SaleOfPropertyPurchase, "", new { #class = "text-danger" })
</div>
</div>
</div>
Here is some sample jquery that reacts to the radio button click, and also sets up initial display on the form:
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('#CurrentPropertyOwner-true').on('change', function () {
$('#CurrentProperty').show();
});
});
$(function () {
$('#CurrentPropertyOwner-false').on('change', function () {
$('#CurrentProperty').hide();
});
});
$(document).ready(function () {
var ischecked = $('#CurrentPropertyOwner-true').is(':checked')
if (ischecked == true) {
$('#CurrentProperty').show();
}
var ischecked = $('#CurrentPropertyOwner-false').is(':checked')
if (ischecked == true) {
$('#CurrentProperty').hide();
}
});
</script>
You need to render two radio buttons for the property, one with the value of "True" and the other with the value of "False" so the selected value can be bound to a boolean value
You custom html helper would need to be
namespace YourAssembly.Html
{
public static class MyHelpers
{
public static MvcHtmlString BooleanButtonsFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, bool>> expression)
{
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string name = ExpressionHelper.GetExpressionText(expression);
StringBuilder html = new StringBuilder();
// Yes button
string id = string.Format("{0}-yes", name);
html.Append(helper.RadioButtonFor(expression, "True", new { id = id }));
html.Append(helper.Label(id, "Yes"));
// No button
id = string.Format("{0}-no", name);
html.Append(helper.RadioButtonFor(expression, "False", new { id = id }));
html.Append(helper.Label(id, "No"));
// enclode in a div for easier styling with css
TagBuilder div = new TagBuilder("div");
div.AddCssClass("radiobuttongroup");
div.InnerHtml = html.ToString();
return MvcHtmlString.Create(div.ToString());
}
}
}
then add a reference to the <namespaces> section of web.config
<add namespace="YourAssembly.Html "/>
and use it in the view
#Html.BooleanButtonsFor(m => m.YourBoolProperty)
I'm having two dropdown lists in my MVC(Razor) view: Country and State.
I'm able to fill both the dropdown's independent of each other.Now i want to fill second dropdown(State) based on the change event of Country's dropdown.
For this I have used JsonResult method in Controller and for this method i'm passing countryID on the Change event of Country from my view inorder to fill my second dropdown state.
Problem Statement: The JsonResult method is getting triggered from my view but the CountryId value is not getting passed from view to controller in-order to fill state.
What i'm doing wrong here?
View:
Javascript:
<script type="text/JavaScript">
function CountryChange() {
var url = '#Url.Content("~/MasterConfigGeneral/GetState")';
var ddlsource = "#CountryID";
var ddltarget = "#StateID";
if ($(ddlsource).val() != "") {
$.ajaxSetup({ cache: false });
$.getJSON(url, { countryID: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$("#StateID").append("<option value=''>Select State</option>");
$.each(data, function (index, optionData) {
$("#StateID").append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
});
});
}
else {
$("#StateID").empty();
$("#StateID").append("<option value=''>Select State</option>");
}
}
</script>
Dropdown's in my View:
<div class="cssclass">
#Html.DropDownListFor(model => model.companyModel.CountryID, new SelectList(Model.ddlCountryStateCity.ddlCountry, "Value", "Text"), "Select Country", new { onchange="CountryChange()" })
#Html.ValidationMessageFor(model => model.companyModel.CountryID)
</div>
<div class="cssclass">
#Html.LabelFor(model => model.companyModel.StateID)
</div>
<div class="editor-field">
#Html.DropDownList("stateid",Model.ddlCountryStateCity.ddlState,"Select State")
#Html.ValidationMessageFor(model => model.companyModel.StateID)
</div>
Controller:
Country Dropdown:
#region Country
public DropdownListCountryStateCity FillDropDownListCountry()
{
objDropDownCountryStateCity.ddlCountry = (from s in dbEntity.Countries
select new SelectListItem()
{
Text = s.Name,
Value = s.CountryID
}).ToList<SelectListItem>();
return objDropDownCountryStateCity;
}
#endregion
State Dropdown:
#region State
public JsonResult GetState(string countryID)
{
JsonResult jsResult = new JsonResult();
objDropDownCountryStateCity.ddlState = (from csc in dbEntity.CountryStateCities
join c in dbEntity.Countries on csc.CountryID equals c.CountryID
join s in dbEntity.States on csc.StateID equals s.StateID
where csc.CountryID == countryID
select new SelectListItem()
{
Text = s.Name,
Value = s.StateID
}).ToList<SelectListItem>();
jsResult.Data = objDropDownCountryStateCity.ddlState;
jsResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jsResult;
}
#endregion
Your problem lies on how the DropDownListFor helper generates the element.
In your code, it's generating names and ids something like this:
<select id="companyModel_CountryID" name="companyModel.CountryID">
...
</select>
In your javascript the ddlSouce is "#CountryID". Since there's no element with that id, jQuery pass null as data to $.getJSON. That's why the controller method receives nothing.
You have two options:
Change ddlSource javascript to the proper id (you'll have to see on the source code) OR
Change the last DropDownListFor helper from
new { onchange="CountryChange()" }
to
new { id = "CountryID", onchange="CountryChange()" }
IMHO, the last option is the best choice.