Dynamically create multiple textbox from dropdownlist entry - c#

I am trying to create multiple textbox from dropdownlist value in C#. Below is my code. whenever I am selecting a value in dropdown list its not showing any textbox. Thanks in advance
<div class="form-group2">
#Html.LabelFor(m => m.AdditionalGuest, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.AdditionalGuest, new List < SelectListItem >{
new SelectListItem { Text = "0", Value = "0" },
new SelectListItem { Text = "1", Value = "1" },
new SelectListItem { Text = "2", Value = "2" },
new SelectListItem { Text = "3", Value = "3" },
new SelectListItem { Text = "4", Value = "4" },
new SelectListItem { Text = "5", Value = "5" }
}, new { #id = "guests" })
</div>
</div>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js">
$("#guests").change(function(){
for(i=0;i<parseInt($(this).val();i++){
$('.form-group2').append('<div class="form-group"><br>#Html.LabelFor(m => m.AdditionalGuestName, new { #class = "col-md-2 control-label" })<br><div class="col-md-10"><br>#Html.TextBoxFor(m => m.AdditionalGuestName, new { #class = "form-control" })</div></div>');
}
}
</script>

#saikat check the below solution
<div class="form-group2">
#Html.LabelFor(m => m.AdditionalGuest, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.AdditionalGuest, new List<SelectListItem>{
new SelectListItem { Text = "0", Value = "0" },
new SelectListItem { Text = "1", Value = "1" },
new SelectListItem { Text = "2", Value = "2" },
new SelectListItem { Text = "3", Value = "3" },
new SelectListItem { Text = "4", Value = "4" },
new SelectListItem { Text = "5", Value = "5" }
}, new { #id = "guests" })
</div>
</div>
<br/>
<div class="form-group3">
</div>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script>
$("#guests").change(function () {
$('.form-group3').html("");
for (i = 0; i < parseInt($(this).val()) ; i++) {
$('.form-group3').append('<div class="form-group"><br>#Html.LabelFor(m => m.AdditionalGuestName, new { #class = "col-md-2 control-label" })#Html.TextBoxFor(m => m.AdditionalGuestName, new { #class = "form-control" })</div>');
}
});
</script>
There is a problem with your script.

Related

ASP.NET MVC : selected value not working on a List<SelectListItem>

I have a list of month like this
public static class Fecha
{
public static IEnumerable<SelectListItem> Meses()
{
List<SelectListItem> meses = new List<SelectListItem>();
meses.Add(new SelectListItem { Text = "Enero", Value = "1" });
meses.Add(new SelectListItem { Text = "Febrero", Value = "2" });
meses.Add(new SelectListItem { Text = "Marzo", Value = "3" });
meses.Add(new SelectListItem { Text = "Abril", Value = "4" });
meses.Add(new SelectListItem { Text = "Mayo", Value = "5" });
meses.Add(new SelectListItem { Text = "Junio", Value = "6" });
meses.Add(new SelectListItem { Text = "Julio", Value = "7" });
meses.Add(new SelectListItem { Text = "Agosto", Value = "8" });
meses.Add(new SelectListItem { Text = "Septiembre", Value = "9" });
meses.Add(new SelectListItem { Text = "Octubre", Value = "10" });
meses.Add(new SelectListItem { Text = "Noviembre", Value = "11" });
meses.Add(new SelectListItem { Text = "Diciembre", Value = "12" });
return meses;
}
}
And I save it in a Viewbag so I can pass it to the view like this
[HttpGet]
public ActionResult Tirilla()
{
int mes = DateTime.Now.Month;
ViewBag.mes = new SelectList(Fecha.Meses(), "Value", "Text", mes);
Tirillas tirillas = new Tirillas();
List<Tirillas> view = new List<Tirillas>();
return View(view);
}
And in my view a read it like this
<div class="col-xs-10">
<label>Mes</label>
<div class="search">
<div id="custom-search-input">
<div class="input-group">
#Html.DropDownList("mes", (IEnumerable<SelectListItem>)ViewBag.mes, new { #class = "form-control" })
<span class="input-group-btn">
<button type="submit" class="btn btn-info btn-lg">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</div>
</div>
</div>
Now, the problem is that on the [HttpGet] of my controller method does not load the selected value, but in the [HttpPost] it does.
I check the code and it goes with the selected values all the time. But as i said in the get it load with Enero. the first value of the list despite having another selected.
Any clues?
I solve it using Session variable instead of viewbag.
I change this
ViewBag.mes = new SelectList(Fecha.Meses(), "Value", "Text", mes);
for this
Session["mes"] = new SelectList(Fecha.Meses(), "Value", "Text", mes);

ASP.NET MVC 5 Nullable boolean as dropdown - parameters

I have a nullable bool in my model
public bool? Property { get; set; }
And I render it via EditorFor
#Html.EditorFor(model => model.Property)
How can I add class form-control to rendered select and how can I localize strings Not set, True and False? Or better how can I replace them with custom strings?
#Html.DropDownListFor(m => m.Property, new SelectList(new[]
{
new SelectListItem { Value = null, Text = "Not set" },
new SelectListItem { Value = false, Text = "False" },
new SelectListItem { Value = true, Text = "True" },
},
"Value",
"Text"
),
new { #class = "form-control" })
You can try with below code:
#Html.DropDownListFor(m => m.Property,
new List<SelectListItem>(){
new SelectListItem { Value = "False", Text = "False" },
new SelectListItem { Value = "True", Text = "True" }
},"Not set",new { #class = "form-control" })

MVC - Show list of strings in DropDownList

Based on this code (auto-generated Control/View code from Visual Studio):
<div class="form-group">
#Html.LabelFor(model => model.Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*Comment: Want to replace EditorFor to DropDownList("Banana, "Apple", "Orange"*#
#Html.EditorFor(model => model.Type, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.Type, "", new { #class = "text-danger" })
</div>
</div>
I would like to add something similar like:
#Html.DropDownList("UserId", null, htmlAttributes: new { #class = "form-control" })
(also auto-generated code, but for UserId) instead of #html.EditorFor...
I was able to see list of UserName(value = Id) from db via Controller:
ViewBag.UserId = new SelectList(db.Users, "Id", "UserName", Test.UserId);
Now, I don't want that ViewBag read from database, instead I want it to list 3 different strings that I will use to let user to chose for indata(meaning, limit them to choice one of these 3 string instead writing it).
Strings I want it to list:
"Banana"
"Apple"
"Orange"
How do I do that?
Try this,
#Html.DropDownList("DropDown", new List<SelectListItem>
{ new SelectListItem { Text = "Banana", Value = "1", Selected=true},
new SelectListItem { Text = "Apple", Value = "2"},
new SelectListItem { Text = "Orange", Value = "3"}
}, "Select Fruit")
OR
Get value in model
#Html.DropDownListFor(x => x.Id, new List<SelectListItem>
{ new SelectListItem { Text = "Banana", Value = "1", Selected=true},
new SelectListItem { Text = "Apple", Value = "2"},
new SelectListItem { Text = "Orange", Value = "3"}
}, "Select Fruit")
Simply change what you are assigning to ViewBag.UserId f.e. like this:
var fruits = new List<string> { "Banana", "Apple", "Orange" };
ViewBag.Fruits = fruits.Select(f => new SelectListItem { Text = f, Value = f });
This is how you can build your list items:
ViewBag.Fruits = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Banana", Value = 0},
new SelectListItem { Selected = false, Text = "Apple", Value = 1},
}, "Value" , "Text", 1);
Here is another way of doing it using enum
public enum Fruit { Banana, Apple, Orange }
#Html.DropDownList("FruitSelection",
new SelectList(Enum.GetValues(typeof(Fruit))),
"Select Fruit",
new { #class = "form-control" })
MVC Controler
ViewBag.PageSort = new List <SelectListItem> ()
{
new SelectListItem () {Value = "1", Text = "Discounts"},
new SelectListItem () {Value = "2", Text = "New Items"},
new SelectListItem () {Value = "3", Text = "Lowest Price"},
new SelectListItem () {Value = "4", Text = "Highest Price"}
};
in View
#Html.DropDownList("PageSort", ViewBag.PageSortas SelectList, "- Select Sort -", new { #id = "SortID", #name = "SortID", #class = "form-control" })

Getting drop down city list to show after state is selected ASP MVC5

I feel like I have a working idea but I am getting a "Object reference not set to an instance of an object" error when I build the application. I am simply trying to display a drop down list for cities after the selection for state is made. I have a list of states in a seperate class that I am using for a drop down list in a form. What I am attempting to do is grab the selected state and pass it as a perameter into a different class in order to select the correct list of cities to be displayed as another drop down. So if someone selects washington state then cities such as Seattle and Tacoma show up and not cities from a different state. Here is the razor for the drop downs (the state works fine):
<div class="form-group">
#Html.LabelFor(model => model.State, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.State, WebGridProject.Models.StateCodes.GetStatesList(), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.State, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.City, WebGridProject.Models.CityNames.GetStateCities(Model.State), new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
And here is the class for cities:
public class CityNames
{
public static IEnumerable<SelectListItem> GetStateCities(string stateName)
{
IList<SelectListItem> cities = new List<SelectListItem>();
switch (stateName)
{
case "AK":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Anchorage", Value = "Anchorage"},
new SelectListItem() {Text = "Fairbanks", Value = "Fairbanks"},
};
break;
case "AL":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Auburn", Value = "Auburn"},
new SelectListItem() {Text = "Birmingham", Value = "Birmingham"},
new SelectListItem() {Text = "Dothan", Value = "Dothan"},
new SelectListItem() {Text = "Mobile", Value = "Mobile"},
};
break;
case "AZ":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Pheonix", Value = "Pheonix"},
new SelectListItem() {Text = "Flagstaff", Value = "Flagstaff"},
new SelectListItem() {Text = "Prescott", Value = "Prescott"},
new SelectListItem() {Text = "Tucson", Value = "Tucson"},
};
break;
case "AR":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Fayetteville", Value = "Fayetteville"},
new SelectListItem() {Text = "Fort smith", Value = "Fort smith"},
new SelectListItem() {Text = "Jonesboro", Value = "Jonesboro"},
new SelectListItem() {Text = "Texarkana", Value = "Texarkana"},
};
break;
default:
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Please Select State", Value = "Please Select State"},
};
break;
}
return cities;
}
}
to me the error seemed to be pointing to there being no default value and having an issue with loading a null value. But I have a default case in the switch statement to cover this issue. I am pretty new to MVC and I will continue to work on this on my own. But if anyone has any ideas I am all ears because I am struggling to figure this out. Just FYI, the states class is also an IList<> that returns the list of state names.
request for action to be posted:
public ActionResult MyHomePage()
{
return View();
}
//Post method
[HttpPost]
public ActionResult MyHomePage(WebGridTable TWG)
{
try
{
if (ModelState.IsValid)
{
UserManager UM = new UserManager();
UM.addNewUser(TWG);
ModelState.Clear();
return View();
}
return View();
}
catch (Exception e)
{
return View("Error");
}
}
action doesnt really mean anything without the method I wrote for managing the form:
public void addNewUser(WebGridTable AddNew)
{
using (WebGridDBEntities4 db = new WebGridDBEntities4())
{
WebGridTable TWG = new WebGridTable();
TWG.Name = AddNew.Name;
TWG.DOB = AddNew.DOB;
TWG.AddressLine1 = AddNew.AddressLine1;
// TO DO: Figure out issue with accepting null value into database.
if (AddNew.AddressLine2 != null)
{
TWG.AddressLine2 = AddNew.AddressLine2;
}
else if (AddNew.AddressLine2 == null)
{
TWG.AddressLine2 = 0;
}
TWG.State = AddNew.State;
TWG.City = TWG.City;
TWG.Zip = AddNew.Zip;
TWG.Gender = AddNew.Gender;
db.WebGridTables.Add(TWG);
db.SaveChanges();
}
}
You need to use JQuery actions on Changes of the States DropDownList. Send the value to a specific Action in your Controller and Call your States.GetStatesName('Value') in that. Check the Code below. I think it would help.
$("#State").on('change',function () {
var loadingoption = $('<option></option>').text("Pleas Wait");
$('#city').attr("disabled","disabled").empty().append(loadingoption);
jQuery.getJSON("/Home/CityJson/" + $("#State > option:selected").attr("value"), function (data) {
var defaultoption = $('<option value="">Please choose a City</option>');
$('#city').removeAttr("disabled").empty().append(defaultoption);
jQuery.each(data, function (i) {
var option2 = $('<option></option>').attr("value", data[i].Name).text(data[i].Name);
$("#city").append(option2);
});
});
});
I used ActionResult "CityJson" in my HomeController. So choose your Action in getJSON.
Here is the Controller:
public ActionResult CityJson(string id)
{
var state = db.States.FirstOrDefault(x => x.Name == id);
var model = db.Cities.Where(x => x.StateId == state.Id).Select(x => new { x.Name }).ToList();
return Json(model, JsonRequestBehavior.AllowGet);
}
you can call your actions inside the Class and send them using Json.
Good Luck.

How to selected value true in dropdownlist MVC

i have problem in dropdownlist selected value.
View
#Html.DropDownList("QuestionType", (IEnumerable<SelectListItem>)ViewData["questiontype"], new { id = "QuestionType", #style = "max-width: 200px;width: 200px", #OnChange = "HideForm(this)", #class = "form-control" })
Controller
var questionTypeList = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "Automatic", Selected = false },
new SelectListItem { Value = "2", Text = "Custom", Selected = true}
}, "Value", "Text"
).ToList();
var questionType = new SelectList(questionTypeList, "Value", "Text");
ViewData["questiontype"] = questionType;
i want value=2 is selected true in view but my script above is not working, how can i solve this problem?
i have modified my code. i'm not using stronglytype which bind to dropdownlist. i'm using viewdata. this is my code:
Controller
List<SelectListItem> questionTypeList = new List<SelectListItem>();
questionTypeList.Add(new SelectListItem() { Text = "Automatic", Value = "1" });
questionTypeList.Add(new SelectListItem() { Selected = true, Text = "Custom", Value = "2" });
ViewData["questiontype"] = questionTypeList;
View
#Html.DropDownList("QuestionType", ViewData["questiontype"] as SelectList, new { id = "QuestionType", #style = "max-width: 200px;width: 200px", #OnChange = "HideForm(this)", #class = "form-control" })
why this code work and why previous code not work? i'm so confuse...
Not sure if you have a strongly typed view but you can use
DropdownlistFor(model=>model.QuestionType, selectlistItem)
then in your controller set
model.QuestionType to 2;
then
return View(model);

Categories