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);
Related
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" })
I am currently writing a search function to search tickets by a Ticket owner, Ticket Tech, Status, etc. However I thought I can just put in if statements in the middle of the Linq statement testing if not null, unfortunately I am getting an error on the if statement that I have in the LINQ statement. Here is my controller code:
public ActionResult TechSearchTickets()
{
ViewBag.StatusId = new SelectList(db.TicketStatuses, "UserId", "FullName");
ViewBag.UserId = new SelectList(db.Users
.Where(u => u.Status == 1 || u.RoleID == new Guid("00000000-0000-0000-0000-000000000000")), "UserId", "FullName");
ViewBag.TechId = new SelectList(db.Users
.Where(u => u.Status == 1 || u.RoleID == new Guid("00000000-0000-0000-0000-000000000000")), "UserId", "FullName");
return View();
}
[HttpPost]
public ActionResult TechSearchTickets(SearchTickets searchTickets)
{
var model = db.Tickets
.Include(t => t.TicketNotes)
if (searchTickets.TechnicianId != null)
{
.Where(t => t.TechnicianId == g)
}
.Where(t => t.TicketStatusId == new Guid("553F4C93-4A72-44BD-A9CE-FAB4F87D4E08"))
.OrderBy(t => t.OpenDate)
.ToList();
return View("TechClosed", model);
return View();
}
Close. You just need to add a few semicolons, and model=models.
var model = db.Tickets
.Include(t => t.TicketNotes);
if (searchTickets.TechnicianId != null)
{
model=model.Where(t => t.TechnicianId==g);
}
model=model.Where(t => t.TicketStatusId==new Guid("553F4C93-4A72-44BD-A9CE-FAB4F87D4E08"))
.OrderBy(t => t.OpenDate);
var result=model.ToList();
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?
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
MovieStoreEntities MovieDb = new MovieStoreEntities();
public ActionResult Edit(int id)
{
//var EditMovie1 = MovieDb
AddMovieModel EditMovie = (from M in MovieDb.Movies
from C in MovieDb.Categories
where M.CategoryId == C.Id
where M.Id == id
select new AddMovieModel { Name = M.Name, Director = M.Director, Country = M.Country, categorie = C.CategoryName, Category = M.CategoryId }).FirstOrDefault();
//AddMovieModel EditMovie1 = MovieDb.Movies.Where(m => m.Id == id).Select(m => new AddMovieModel {m.Id }).First();
List<CategoryModel> categories = MovieDb.Categories
.Select(category => new CategoryModel { Category = category.CategoryName, id = category.Id })
.ToList();
ViewBag.Category = new SelectList(categories, "Id", "Category");
return View(EditMovie);
}
//
// POST: /Default1/Edit/5
[HttpPost]
public ActionResult Edit(AddMovieModel Model2)
{
List<CategoryModel> categories = MovieDb.Categories
.Select(category => new CategoryModel { Category = category.CategoryName, id = category.Id })
.ToList();
ViewBag.Category = new SelectList(categories, "Id", "Category");
if (ModelState.IsValid)
{
//MovieStoreEntities model = new MovieStoreEntities();
MovieDb.SaveChanges();
return View("Thanks2", Model2);
}
else
return View();
}
This is the Code that I have wrote to edit Movie details and update database in the sql server.
This dont have any compile errors, But It didnt update sql server database.
Presuming here you are updating a category you would need to do something like
List<CategoryModel> categories = MovieDb.Categories
.Select(category => new CategoryModel { Category = category.CategoryName, id = category.Id })
.ToList();
ViewBag.Category = new SelectList(categories, "Id", "Category")
Category category = new Category()
category = categories.First(p=>p.CategoryId == Id);
category.Name = "New Name";
MovieDb.Categories.SaveChanges(category);
MovieDb.SaveChanges();
You will need to get the item you are wanting to edit...in this case a category which would be filtered from the list of categories. You can then call the savechanges method on that entity i.e. MovieDb.Categories.SaveChanges() and pass through the item that you want to update.
You need to use the Model2 object to create a new entity, add it to the ObjectContext and save the changes. You haven't written any code that should save anything to a database.