Appending Default Value to dropdownlistfor - MVC 4 razor - c#

How do I append default value to the my dropdownlistfor using the code below
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetCitiesByStateId(int stateId)
{
if (stateId==0)
{
throw new ArgumentNullException("stateId");
}
var x = _repository.GetAllCitiesByStateId(stateId);
var result = (from s in x
select new
{
id = s.id,
name = s.CityName
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
My view code looks like this:
#Html.DropDownListFor(x => x.City.ID, Model._Cities)
#Html.ValidationMessageFor(x => x.City)
Thanks anticipation

Related

How to convert Ienumerable<system.web.mvc.selectedlistitem> to Generic.List<system.web.mvc.selecteditemlist>?

Cannot implicitly convert type
'System.Collection.Generic.Ienumerable<system.web.mvc.selectedlistitem>'
to 'System.Collections.Generic.List<system.web.mvc.selecteditemlist>'
I am trying to make a selectedlistitem for View model to make a dropdownmenu.
ViewModel of SurveyResult
public List<SelectListItem> SurveyMasterList { get; set; }
MasterList takes value from database
var MasterList = _mcniDbContext.SurveyMaster.Where(e => e.SurveyMasterId == tempCustomer.SurveyMasterId).ToList();
The error comes at the code below.
temp.SurveyMasterList = MasterList.Select(m => new SelectListItem { Text = m.SurveyName, Value = m.SurveyMasterId.ToString() });
Assuming that temp.SurveyMasterList is List of SelectListItem too, just fix your second query by adding ToList();
temp.SurveyMasterList = MasterList
.Select(m => new SelectListItem { Text = m.SurveyName, Value = m.SurveyMasterId.ToString() })
.ToList();
but it is better to merge both queries
temp.SurveyMasterList = _mcniDbContext.SurveyMaster
.Where(e => e.SurveyMasterId == tempCustomer.SurveyMasterId)
.Select(m => new SelectListItem { Text = m.SurveyName, Value = m.SurveyMasterId.ToString() })
.ToList();
You can define your List<SelectListItem> as IEnumerable<SelectListItem> in your view model. Then in your controller fill it like this :
viewmodelobject.SurveyMasterList = new SelectList(_mcniDbContext.SurveyMaster, "SurveyMasterId", "SurveyName");
In your View, you can use it like this:
#Html.DropDownList("DrpSurvey", Model.SurveyMasterList , "Master List: ", new { #class = "form-control" })

Retrieving all records with Lambda StartsWith()

I have the following ActionResult and retrieve records that starting with "query" parameter's value. However, when quesry value is empty or null, the methods returns no record while I want to retrieve all of them. So, do I have to use a if clause and create different lambda clauses, or is it possible to check query parameter and retrieve all of the records by using StartsWith?
public ActionResult StudentLookup(string query)
{
var students = repository.Students.Select(m => new StudentViewModel
{
Id = m.Id,
Name = m.Name
})
.Where(m => m.Name.StartsWith(query));
return Json(students, JsonRequestBehavior.AllowGet);
}
Well, two options:
Conditionally apply the Where clause:
IQuerable<StudentModel> students = repository.Students.Select(m => new StudentViewModel
{
Id = m.Id,
Name = m.Name
});
if (!string.IsNullOrEmpty(query))
{
students= students.Where(m => m.Name.StartsWith(query));
}
return Json(students, JsonRequestBehavior.AllowGet);
Put the check in the Where clause itself:
var students = repository.Students.Select(m => new StudentViewModel
{
Id = m.Id,
Name = m.Name
})
.Where(m => string.IsNullOrEmpty(query) || m.Name.StartsWith(query));
return Json(students, JsonRequestBehavior.AllowGet);

How to Bind a DropDownList Text Value to another DropDownList using Kendo UI for MVC?

I'm using the Kendo UI for ASP.NET MVC and need to bind the selected value of a dropdown list to another dropdownlist. I want the user to only be shown the citiy entries that are applicable to the State selection they choose. My dropdownlist is as follows:
<div id="bindcity" class="inr_div" data-bind="visible: showFromChooseCity">
<h5 class="inr_hd">City<span>*</span>:</h5>
#(Html.Kendo().DropDownList()
.Name("fromCity")
.DataTextField("name")
.DataValueField("id")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCity", "Quote");
})
.ServerFiltering(true);
})
.SelectedIndex(0)
)
I setup several controller classes as follows:
public JsonResult GetZips()
{
FreightEntities freight = new FreightEntities();
var zips = freight.ZipCodes.AsQueryable();
var city = freight.ZipCodes.AsQueryable();
if (city != null)
{
zips = zips.Where(z => z.Zip = zips);
}
return Json(freight.ZipCodes.Select(z => new {Zip = z.Zip}), JsonRequestBehavior.AllowGet);
}
public JsonResult GetCity()
{
FreightEntities freight = new FreightEntities();
var state = freight.ZipCodes.AsQueryable();
var city = freight.ZipCodes.AsQueryable();
if (state != null)
{
city = city.Where(s => s.State = state);
}
return Json(freight.ZipCodes.Select(s => new { State = s.State }), JsonRequestBehavior.AllowGet);
}
public JsonResult GetState()
{
FreightEntities freight = new FreightEntities();
return Json(freight.ZipCodes.Select(s => new {State = s.State }), JsonRequestBehavior.AllowGet);
}
The above code now gives the error:
Cannot implicitly convert type 'System.Linq.IQueryable<FRCV2.Models.ZipCode>' to 'string'
Since I'm not using an ID field in my entities, what's the appropriate way of comparing the fields above?
How do I achieve this cascading dropdownlist effect?

Dropdownlist Empties on submit button click (Form Post) - Mvc 4 razor using code first approach and EF

I have four dropdownlistfor and a radiobuttonlistfor group. The radiobutton is for location type (which can either be an urban or rural location).
The first dropdownlistfor is the state which a user must select first before choosing either urban or rural. When the radiobuttonlistfor is selected it triggers a jquery click event which calls an action in my controller to populate the second dropdownlistfor for cities under the selected state and location type.
Controller
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetCitiesByStateId(int stateId)
{
if (stateId==0)
{
throw new ArgumentNullException("stateId");
}
var x = _repository.GetAllCitiesByStateId(stateId);
var result = (from s in x
select new
{
id = s.id,
name = s.CityName
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetRuralArea(int stateId)
{
if (stateId == 0)
{
throw new ArgumentNullException("stateId");
}
var x = _repository.GetAllAreaInRural(stateId);
var result = (from s in x
select new
{
id = s.id,
name = s.AreaName
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
View
State:
#Html.DropDownListFor(x => x.State.ID, Model._State(), "Select")
#Html.RadioButton("UrbanRural", "1", false, new { id = "urban" })
#Html.RadioButton("UrbanRural", "2", false, new { id = "rural" })
#Html.DropDownListFor(x => x.City.ID, Model._Cities)
#Html.DropDownListFor(x => x.AreaRural.ID, Model._AreaRural)
Button Click Code
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(Registration model)
{
if (ModelState.IsValid)
{
return RedirectToAction("Confirmation");
}
else
{
ViewBag.Selpwd = model.Password;
return View(model);
}
}
Issue:
I observed that when my button is clicked the city or area dropdownlistfor as the case may be empties. How do I retain the content after a postback?

mvc3 view viewdata and viewbag is null

I can't seem to pass any data via the ViewBag or ViewData to the View. It just keeps coming back with null.
ViewResult code:
public ViewResult EditProduct(Guid id)
{
var product = _repository.Products.FirstOrDefault(x => x.ID == id);
ViewData["Categories"] = _repository.Categories;
ViewData["CategoryList"] = _repository.Categories.Select(x => new SelectListItem { Text = x.Name, Value = x.ID.ToString(), Selected = product.ID == x.ID });
ViewBag.Test = "Hello";
return View(product);
}
and this is the razor code:
#model NightingalecrossMVC.Domain.Entities.Product
#{
var test = ViewData.Eval("CategoryList");
var test2 = ViewBag.Test;
ViewBag.Title = "Edit Treatment";
AjaxOptions ajaxOpts = new AjaxOptions
{
UpdateTargetId = "saveData",
HttpMethod = "Post",
LoadingElementId = "loader"
};
}
Why is this happening? It works fine on any other view?!
The reason for getting null values is because I had this:
public ViewResult CreateProduct()
{
return View("EditProduct", new Product());
}
It needed to be this:
public ViewResult CreateProduct()
{
ViewBag.CategoryList = _repository.Categories.Select(x => new SelectListItem { Text = x.Name, Value = x.ID.ToString() });
return View("EditProduct", new Product());
}
EDIT
Actually you can't make a selectlistitem list like that because of the ToString() method in the LINQ, it needs to be elongated with {} instead of new SelectListItem to make a proper function out of it. But then this will decrease readability. So the best solution is to make a function that returns IEnumerable then you can make a SelectList.
There has been some controversy about using SelectList and that DropDownList doesn't support that overload. However SelectList does implement IEnumerable so shouldn't therefore support SelectList.

Categories