I have a model with two lists of SelectListItems:
public List<SelectListItem> ChosenLanguages { get; set; }
public List<SelectListItem> ChosenTemplates { get; set; }
I create checkboxes from those two lists for the user to interact with:
<div class="row">
<div class="col-lg-3">
<h5>Select languages for certificates</h5>
<div class="row" style="width:100%">
#for (int i = 0; i < Model.ChosenLanguages.Count; i++)
{
<div class="col-md-4">
#Html.CheckBoxFor(x => x.ChosenLanguages[i].Selected)
#Html.DisplayFor(x => x.ChosenLanguages[i].Text)
#Html.HiddenFor(x => x.ChosenLanguages[i].Value)
#Html.HiddenFor(x => x.ChosenLanguages[i].Text)
</div>
}
</div>
</div>
<div class="col-lg-3">
<h5>Select templates for certificates</h5>
<div class="row" style="width:100%">
#for (int i = 0; i < Model.ChosenTemplates.Count; i++)
{
<div class="col-md-5">
#Html.CheckBoxFor(x => x.ChosenTemplates[i].Selected)
#Html.DisplayFor(x => x.ChosenTemplates[i].Text)
#Html.HiddenFor(x => x.ChosenTemplates[i].Value)
#Html.HiddenFor(x => x.ChosenTemplates[i].Text)
</div>
}
</div>
</div>
</div>
Now I want to have a new checkbox that will "onclick" deselect all the checkboxes created above (as the use case requires the user to only select 1 language and 1 template):
#Html.CheckBoxFor(model => model.SerialOnly, new { htmlAttributes = new { #class = "form-control", #onclick = "clearSelected();" } })
My question is how do I go about deselecting each checkbox from the model in the view through an onclick? I have tried to use JavaScript and JQuery but I cannot figure out how I would access the individual checkboxes in the List..
I have tried to use the code from the most upvoted answer on this post (the accepted solution does not seem to fit my layout):
$(document).on('click', '#SelectAllCheckBox', function () {
$('.Publications input[type=checkbox]').toggle(this.checked);
});
Where I added the Publications name as a class to my checkboxes like so:
#Html.CheckBoxFor(x => x.ChosenTemplates[i].Selected, new { htmlAttributes = new { #class = "Publications" } })
And added the id to the new checkbox:
#Html.CheckBoxFor(model => model.SerialOnly, new { htmlAttributes = new { #class = "form-control", #id = "SelectAllCheckBox", #onclick = "clearSelected();" } })
But this did not work either. I know it will select all instead of deselect, but I just wanted to make the functionality work before changing it to deselect. Any ideas?
Related
I am currently trying to populate the values for a car's model based on the selected make in a dropdownlist. I am new to coding so I am not sure what my mistake is. The project doesn't give me any errors but no values are displayed when I selected the make.
This is my Partial View that I am adding into my Create View.
#model IgnitionHubPractice.Models.MakeModelDorpdownView
<div class="form-horizontal">
<div class="form-group">
#if (ViewBag.MakeList != null)
{
#Html.DropDownListFor(m => m.MakeID, ViewBag.MakeList as SelectList, "--Select Make--", new { #class = "form-control" })
}
</div>
<div class="form-group">
#Html.DropDownListFor(m => m.ModelID, new SelectList(" "), "--Select Model--", new { #class = "form-control" })
</div>
</div>
<script>
$(document).ready(function () {
$("#MakeID").change(function () {
$.get("/Cars/GetModelList",{ MakeID: $("MakeID").val() }, function (data) {
$("#ModelID").empty();
$.each(data, function (index, row) {
$("#ModelID").append("<option value ='" + row.ModelID + "' >" + row.Name + </option>")
});
});
})
});
</script>
This is my controller
public ActionResult Create([Bind(Include = "CarID,Year,Color,Mileage,Cost,MarketValue,BodyType,Drive,Notes,Available,VinNumber,CarLotID,ModelID")] Car car, [Bind(Include ="MakeID,Name")] Make make)
{
if (ModelState.IsValid)
{
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
List<Make> MakeList = db.Makes.ToList();
ViewBag.MakeList = new SelectList(db.Makes, "MakeID", "Name", make.MakeID);
ViewBag.ModelID = new SelectList(db.Models, "ModelID", "Name", car.ModelID);
ViewBag.CarLotID = new SelectList(db.CarLots, "CarLotID", "LotName", car.CarLotID);
return View(car);
}
public JsonResult GetModelList(int MakeID)
{
db.Configuration.ProxyCreationEnabled = false;
List<Model> ModelList = db.Models.Where(x => x.MakeID == MakeID).ToList();
return Json(ModelList, JsonRequestBehavior.AllowGet);
}
Please help, thanks in advance.
In MVC you try to create a cascading drop down. So for easy understanding you can check the below link. It contanin detailed information for controller and View with Jquery part.
Please visit this link: Cascading Drop down List With MVC And AJAX
I am trying to append a number of dropdowns on Button click.These dropdowns should have proper indexing in its 'name' attribute.
This is the dropdown:-
<div id="dropdownDiv" style="display:none">
<div class="form-group">
#Html.LabelFor(model => model.PropertyInvestors, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.PropertyInvestors, (IEnumerable<SelectListItem>)#ViewBag.Investors, "Select Investor", htmlAttributes: new { #id = "dropdown",#name= "[#].PropertyInvestors", #class = "form-control",#onChange="dropdownChange()" })
#Html.ValidationMessageFor(model => model.PropertyInvestors, "", new { #class = "text-danger" })
</div>
</div>
</div>
This is the JS code that I am trying in order to clone the dropdown and replace its name attribute with desired indexing.
$('#addDropdown').click(function () {
var index = (new Date()).getTime();
var clone1 = $('#dropdownDiv').clone();
clone1.html($(clone1).html().replace(/\[#\]/g, '[' + index + ']'));
$('#field1').append(clone1.html());
});
Problem:- The dropdowns are being appended as they are clicked but their name attributes are same for all of the dropdowns produced due to which I cant postback the data to the controller.
While this problem can be solved by using dummy code and manipulating the Index no. by using JS, a good method would be to use Html.BeginCollectionItem() by creating a partial view for the dropdown and later making an ajax call to append the partial view to the main view. Refer to the answer HERE
You can replace ID and Name as follows:
$('#addDropdown').click(function () {
var index = (new Date()).getTime();
var clone1 = $('#dropdownDiv').clone();
$(clone1).find('select').attr("id", index);
$(clone1).find('select').attr("name", "PropertyInvestor[" + index +"]");
$('#field1').append(clone1.html());
});
JSFiddler: https://jsfiddle.net/qj24yybe/6/
I’m new to MVC and I’m having a lot of trouble with Partial Views. Hopefully someone can give me some guidance.
We’re trying to port our ASP.Net webforms app to MVC. I’ve created a little test app to try to mimic what we’re doing on many of our pages. Based on sample code I found here, I have a View and a Partial view and a Model that contains the Partial model. The view has a drop down list that hides/shows the partial view.
When the user selects Hidden, I have a javascript method that hides the partial view. If they select Visible, the javascript makes a call to an action where I want to be able to modify the model and send it back to the view. I will also need to be able to hide or show other partial views on the page. In another scenario, I will need to be able to modify TestModel and PartialModel within the javascript function itself and re-render (have the changes reflected to the user).
I currently have two things I can't figure out:
How to access the model in the javascript function
How to pass the model back and forth to the action called from the model
The code, as it stands now, calls the action in which I create a new PartialModel and pass it back to the view. That works but when I click on the save button, the "old" PartialModel is passed to the HTTPPost action. However, I need to modify the existing model and not create a new one.
I've posted the code below. Any help would be greatly appreciated.
Controller
namespace WebApplication1.Controllers
{
public class TestController : Controller
{
// GET: Test
public ActionResult Index()
{
TestModel tm = new TestModel();
tm.Vis = Visibility.Visible;
return View(tm);
}
[HttpPost]
public ActionResult Index(TestModel tm)
{
return View(tm);
}
public ActionResult DDLChangedAction(int id)
{
// I need access to TestModel including TestModel.PartialModel
var pvm = new PartialModel();
pvm.PartialInt = 100;
pvm.PartialString = id.ToString(); ;
pvm.PartialString2 = "asdf";
////return PartialView("_PartialTest", pvm,
//// new ViewDataDictionary(System.Web.Mvc.Html.HtmlHelper.ViewData)
//// {
//// TemplateInfo = new TemplateInfo { HtmlFieldPrefix = HtmlHelper.NameFor(m => m.Partial).ToString() }
//// });
return PartialView("_PartialTest", pvm);
}
private ActionResult PartialView(string v, PartialModel pvm, ViewDataDictionary viewDataDictionary)
{
throw new NotImplementedException();
}
}
}
Model
namespace WebApplication1.Models
{
public class TestModel
{
public TestModel()
{
Partial = new PartialModel();
Partial.PartialInt = 42;
Partial.PartialString = "partialString text";
Partial.PartialString2 = "partialString2 text";
}
public int SelectedItem { get; set; }
public Visibility Vis { get; set; }
public PartialModel Partial { get; set; }
}
public class PartialModel
{
public int PartialInt { get; set; }
public string PartialString { get; set; }
public string PartialString2 { get; set; }
}
public enum Visibility
{
Visible = 1,
Hidden
}
}
View
<h2>Index</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>TestModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("Visibility", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Vis", new SelectList(Enum.GetValues(typeof(Visibility))),
"Select",
new {
#id = "ddlVis",
#class = "form-control"
//onchange = #"ddlChanged();"
})
</div>
<br />
#Html.LabelFor(model => model.SelectedItem, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SelectedItem, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SelectedItem, "", new { #class = "text-danger" })
</div>
</div>
<div id="partialPlaceHolder">
#Html.Partial("_PartialTest", Model.Partial,
new ViewDataDictionary(Html.ViewData)
{
TemplateInfo = new TemplateInfo { HtmlFieldPrefix = Html.NameFor(m => m.Partial).ToString() }
})
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$('#ddlVis').change(function () {
/* Get the selected value of dropdownlist */
var selectedID = $(this).val();
if (selectedID == 1) {
// access and modify the model and partial model
}
if ($('#ddlVis').val() == "Visible") {
// I can pass an integer here, but how do I pass in the model to the action?
$.get('/Test/DDLChangedAction/' + 123, function (data) {
/* data is the pure html returned from action method, load it to your page */
$('#partialPlaceHolder').html(data);
$('#partialPlaceHolder').show();
});
} else if ($('#ddlVis').val() == "Hidden") {
$('#partialPlaceHolder').hide();
}
});
function ddlChanged() {
alert("projectPtIndChanged")
if ($('#ddlVis').val() == "Hidden") {
alert("in hide");
//debugger;
$("#divHideTest").hide();
// now let's show the partial
var newString = "Ickle";
$.get('/Test/DDLChangedAction' + newString, function (data) {
$('#partialPlaceHolder').html(data);
});
} else {
alert("in show");
$("#divHideTest").show();
}
}
</script>
}
Partial View
#model WebApplication1.Models.PartialModel
<div>
<fieldset>
<legend>PartialTest</legend>
<dl class="dl-horizontal">
<dt>#Html.DisplayNameFor(model => model.PartialInt)</dt>
<dd>#Html.EditorFor(model => model.PartialInt)</dd>
<dt>#Html.DisplayNameFor(model => model.PartialString)</dt>
<dd>#Html.EditorFor(model => model.PartialString)</dd>
<dt>#Html.DisplayNameFor(model => model.PartialString2)</dt>
<dd>#Html.EditorFor(model => model.PartialString2)</dd>
</dl>
</fieldset>
</div>
I've implemented Cascading Drop Down Lists on the Create View page of my MVC Asp.NET Application.
Unfortunately, I am having issues with selecting a value that is located in the JavaScript Array. I need to bind the selected value for the use of one of my controllers.
Right now my List populates, but I have no way to select it. Is there a way to move the counties[i] array from my JavaScript to the #Html.DropDownListFor() helper?
Thanks!
JavaScript:
<script src="#Url.Content("~/Scripts/jquery-1.10.2.min.js")"
type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#county").prop("disabled", true);
$("#StateLongName").change(function() {
if ($("#StateItems").val() != "Please select") {
var options = {};
options.url = "/County/GetCounties";
options.type = "POST";
options.data = JSON.stringify({ state: $("#StateLongName").val() });
options.dataType = "json";
options.contentType = "application/json";
options.success = function(counties) {
$("#county").empty();
for (var i = 0; i < counties.length; i++) {
$("#county").append("<option>" + counties[i] + "</option>");
}
$("#county").prop("disabled", false);
};
options.error = function() { alert("Error retrieving counties!"); };
$.ajax(options);
} else {
$("#county").empty();
$("#county").prop("disabled", true);
}
});
});
</script>
Controller:
//GET Counties for Cascading Dropdown List
public JsonResult GetCounties(string state)
{
var counties = db.countycigtaxes.Join(db.statecigtaxes,
cc => cc.stateid,
sc => sc.stateid,
(cc, sc) => new
{
cc,
sc
}).Where(co => co.sc.statefullname == state)
.Select(co => co.cc.countyfullname).ToList();
return Json(counties);
}
View Page:
<div class="form-group">
#Html.LabelFor(model => model.StateLongName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.StateLongName, Model.StateItems, "Please select")
#Html.ValidationMessageFor(model => model.StateLongName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CountyLongName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor(m => m.CountyLongName, )*#
<select id="county"></select>
#Html.ValidationMessageFor(model => model.CountyLongName)
</div>
</div>
I assume you mean the the selected value of the property CountyLongName is not posting back when you submit the form. You have commented out this line
#Html.DropDownListFor(m => m.CountyLongName, )
and used
<select id="county"></select>
If you want the manual version (I do not recommend this), then you need to add a name attribute that matches the property name so it can be bound by the ModelBinder
<select name="CountyLongName" id="county"></select>
But it is better to use the helper and pass it an empty SelectList
Html.DropDownListFor(m => m.CountyLongName, Model.CountryNames)
where Model.CountryNames is a property in you view model that is initialised to an empty SelectList
Note also options.type = "POST"; should be "GET" and the whole AJAX could be simplified to
$.get('#Url.Action("GetCounties","Country")', { state: $('#StateLongName').val() }, function(countries) {...
and theToList() is not required in the JsonResult method
This should set the option selected for you.
$("#county option[value='" + counties[index] + "']").attr("selected", "selected");
hi i have a partial view that is loaded in main view by clicking "edit" or "create" button.
it hast some dropdownlist thas fill by ViewBags.
i have activated unobtrasive javascript in webconfig and use it in my partial view.
when i debug main view in firebug, DropDownList's validationMessage errors just shows in html part of console and doesn't show in view by
"#Html.ValidationMessageFor(m=>m.groupID)"
how can i solve it? Thanks.
Edited: Sample codes
<div class="editor-label">
#Html.LabelFor(model => model.InsuranceInsurerID)
</div>
<div class="editor-field">
#Html.DropDownList("InsuranceInsurerID", "Select...")
#Html.ValidationMessageFor(model => model.InsuranceInsurerID)
</div>
<div class="clr"></div>
<div class="editor-label">
#Html.LabelFor(model => model.InsuranceTypeID)
</div>
<div class="editor-field">
#(Html.Kendo().ComboBox()
.Name("InsuranceTypeID")
.HtmlAttributes(new { style = "width:210px" })
.Placeholder("Select...")
.DataTextField("TypeName")
.DataValueField("TypeID")
.Filter(FilterType.Contains)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCascadeTypes", "Insurance");
});
})
)
#Html.ValidationMessageFor(model => model.InsuranceTypeID)
</div>
ViewBags:
var InsInsurer = db.INS_InsuranceWorkers
.Where(m => m.InsWorkerTypeID == 1 && m.InsWorkerCreateUserID == userid)
.Select(k => new { FullName = k.InsWorkerFirstName + " " + k.InsWorkerLastName,
InsInsurerID = k.InsWorkerID }).ToList();
ViewBag.InsuranceInsurerID = new SelectList(InsInsurer, "InsInsurerID", "FullName");
kendo dropdown gets list by its actions.