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
Related
I have a search functionality which already works by searching the data that the user requests. I would like to add a clear button for the user to be able to clear the search bar, at the moment the user has to clear the search using the "backspace" button and press "enter to go back the page with all the data. I am a expert in front end so would appreciate some help thank you in advance.
Javascript
$(function () {
$("#SearchString").autocomplete({
source: '#Url.Action("GetUserJSON")',
minLength: 1
})
});
$(function () {
$("#SearchString").focus();
});
$(function () ) {
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close');
});
};
Razor HTML
#using (Html.BeginForm("Index", "User", FormMethod.Get, null))
{
<div class="search-wrap">
#Html.TextBoxFor(m => m.SearchString, new { id = "SearchString", #class = "lookup txt-search js-autocomplete-submit", #placeholder = "Search", #type ="search" })
#*<img src="~/Content/Images/close.png" id ="closebutton"/>*#
<button type="button" id="clearbutton">Click Me!</button>
<i onclick="submitform()" class="btn-search fa fa-search"></i>
</div>
}
C# Class where data get pull from
public JsonResult GetUserJSON(string term)
{
var stores = (from st in UserLogic.GetUserIndex(1, term).IndexList
select new { st.Username, st.FirstName, st.LastName }).ToList();
List<String> returnList = new List<string>();
foreach (var item in stores)
{
if (item.Username.ToString().ToUpper().StartsWith(term.ToUpper()))
{
returnList.Add(item.Username.ToString());
}
else if (item.FirstName.ToUpper().Contains(term.ToUpper()))
{
returnList.Add(item.FirstName);
}
else if (item.Username.ToUpper().Contains(term.ToUpper()))
{
returnList.Add(item.Username);
}
}
returnList = returnList.Distinct().OrderByAlphaNumeric(s => s).ToList();
return Json(returnList, JsonRequestBehavior.AllowGet);
}
I think this is what you need:
$(function () {
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close');
$("#SearchString").val("")
});
});
Add $("#SearchString").val("") to your clearbutton click event
Edit:
You have mistyped the function for clearSearch
this is working example
please try using this
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close').val('');
});
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);
#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" })
I'm srugelling with this,
Working on MVC, upon change on Html.TextBoxFor value I want to change a readonly attribute of another Html.TextBoxFor.
I tried several ways-using IE it does not work.
here some code:
#Html.TextBoxFor(x => x.NumberOfQuestion, new { id = "ExamOptions", onchange = "javascript:ReadOnlyHandle();" })
<script>
function ReadOnlyHandle() {
//document.getElementById("NoDiffNum").readOnly = true;
var startHSelect = document.getElementById("NoDiffNum");
debugger;
startHSelect.setAttribute("readonly", "true");
}
debugger;
</script>
and the row in a table I would like to change:
<td id="NoDiffNum">#Html.TextBoxFor(model => model.Topics[i].NumberOfNoDifficulltySet)</td>
the readonly attribute did not changed -
any help is most welcome!
document.getElementById("NoDiffNum") refers to the <td> element not the text box. You are setting readonly on the td.
You need to target the text box, not the td, so move the id to the text box.
<td>#Html.TextBoxFor(model => model.Topics[i].NumberOfNoDifficulltySet, new { id="NoDiffNum" })</td>
Without jQuery
function ReadOnlyHandle() {
var startHSelect = document.getElementById("NoDiffNum");
startHSelect.setAttribute("readonly", "readonly");
}
And with jQuery in your function
function ReadOnlyHandle() {
$("#NoDiffNum").prop("readonly", true);
}
If we use jQuery we can drop the inline onchange
#Html.TextBoxFor(x => x.NumberOfQuestion, new { id = "ExamOptions" })
And we setup a handler
$(document).ready(function() {
$("#ExamOptions").on("change", function(event) {
ReadOnlyHandle();
});
});
Edit
Based on a value in TextBoxFor element value I want another TextBoxFor element to change its readonly attribute on and off. <div class="editor-field"> #Html.TextBoxFor(x => x.NumberOfQuestion, new { id = "ExamOptions", onchange = "javascript:ReadOnlyHandle();" }) #*#Html.EditorFor(model => model.NumberOfQuestion)*# #Html.ValidationMessageFor(model => model.NumberOfQuestion) </div>
From your comments it's now less clear what you want to set readonly. But in any case you adjust the target id in the change handler.
var targetId = "NumberOfQuestion";
$("#" + targetId).prop("readonly", true);
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)