Search Only if not Null value - c#

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();

Related

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);

Update rows from grid and database with Kendo UI and MVC

I'm using a MVC project with Visual Studio 2012 and Kendo UI 2014.
I can update a row from the grid and it changes, but when I reload the page, the row appears with the original info. I would like to update it in the database too.
This is my code:
.cshtml (View):
<div class="grid">
#(Html.Kendo().Grid<UsersModel>()
.Name("grid")
.Editable(editable => editable.Mode(GridEditMode.InCell))
.DataSource(dataSource => dataSource
.Ajax()
.Model(r => r.Id(p => p.Id))
.Read(r => r.Action("GetAccounts", "ManagerAccounts", new { area = "Admin" }))
.Destroy("Delete", "ManagerAccounts")
.Update("Update", "ManagerAccounts")
.Create("Create", "ManagerAccounts")
)
.Columns(columns =>
{
columns.Bound(c => c.Id);
columns.Bound(c => c.UserName);
columns.Bound(c => c.Email);
columns.Command(command => command.Destroy()).Width(120);
})
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5)
)
.Sortable()
.Navigatable()
.ToolBar(toolbar => {
toolbar.Create();
toolbar.Save();
})
)
</div>
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Update([DataSourceRequest] DataSourceRequest request, IEnumerable<UsersModel> users)
{
if (users != null && ModelState.IsValid)
{
foreach (var user in users)
{
AccountRepository.UpdateUsuarios(user);
}
}
return Json(ModelState.ToDataSourceResult());
}
Repository (AccountRepository):
public void UpdateUsuarios(UsersModel user)
{
var usuario = this.Context.Users.Where(l => l.Id == user.Id).FirstOrDefault();
if (usuario != null)
{
usuario.Id = user.Id;
usuario.UserName = user.UserName;
usuario.Email = user.Email;
this.Context.SaveChanges();
}
}
I tried with this.Context.SaveChanges(); but it doesn't work.
Could you please try this code:
if (usuario != null)
{
usuario.Id = user.Id;
usuario.UserName = user.UserName;
usuario.Email = user.Email;
this.Context.Entry(usuario).State = System.Data.Entity.EntityState.Modified;
this.Context.SaveChanges(); // Or you may try await this.Context.SaveChangesAsync();
}

NopCommerce - Page Navigation Issue with Telerik-Grid

I am using nopCommerce. I have used telerik-grid to bind data in a table and data binded successfully. I have create method named "EditContact" for Edit operation. but when i clicked Edit link to redirect page named "_CreateOrUpdateContact.cshtml", i got "Page not found" page.
telerik-grid code :
#(Html.Telerik().Grid<AddressModel>()
.Name("vendors-grid")
.Columns(columns =>
{
columns.Bound(x => x.CountryName)
.Width(200).Centered();
columns.Bound(x => x.FirstName)
.Width(200).Centered();
columns.Bound(x => x.LastName)
.Width(200).Centered();
columns.Bound(x => x.Title)
.Width(200).Centered();
columns.Bound(x => x.Email)
.Width(200).Centered();
columns.Bound(x => x.PhoneNumber)
.Width(200).Centered();
columns.Bound(x => x.Address1)
.Width(200).Centered();
columns.Bound(x => x.Id)
.Width(200)
.Centered()
.Template(x => Html.ActionLink(T("Admin.Common.Edit").Text, "Edit", new { id = x.Id }))
.ClientTemplate("" + T("Admin.Common.Edit").Text + "")
.Title(T("Admin.Common.Edit").Text);
columns.Bound(x => x.Id)
.Template(x => Html.ActionLink(T("Admin.Common.Delete").Text, "Delete", new { id = x.Id }))
.ClientTemplate("" + T("Admin.Common.Delete").Text + "")
.Centered().Width(200)
.HeaderTemplate(T("Admin.Common.Delete").Text);
})
.Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
.DataBinding(dataBinding => dataBinding.Ajax().Select("ListContacts", "VendorDetails",new { vendorId = Model.Id }))
.EnableCustomBinding(true))
EditContact.cshtml Code:
#model AddressModel
#using (Html.BeginForm())
{
<div class="section-header">
<div class="options">
<input type="submit" name="save" class="t-button" value="#T("Admin.Common.Save")" />
<input type="submit" name="save-continue" class="t-button" value="#T("Admin.Common.SaveContinue")" />
</div>
</div>
#Html.Partial("_CreateOrUpdateContact", Model)
}
#Html.DeleteConfirmation("vendor-delete")
VendorDetailsController Methods:
[HttpPost, GridAction(EnableCustomBinding = true)]
public ActionResult ListContacts(int vendorId,GridCommand command)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageVendors))
return AccessDeniedView();
var Addresses = _addressService.GetVendorAddresses(vendorId);
var gridModel = new GridModel<AddressModel>
{
Data = Addresses.Select(x =>
{
var a = new AddressModel();
PrepareAddressModel(a, x, false);
return a;
}),
Total = Addresses.Count,
};
return new JsonResult
{
Data = gridModel
};
}
// edit vendor contact
public ActionResult EditContact(int id)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageVendors))
return AccessDeniedView();
var address = _addressService.GetAddressById(id);
int vendorId = _vendorContactService.GetVendorIdByAddressId(address.Id);
if (address == null)
//No Address found
return RedirectToAction("Edit", new { id = vendorId });
var model = new AddressModel();
model.VendorId = vendorId;
//Ordering Method
model.AvailableCountries.Add(new SelectListItem() { Text = "-- Select --", Value = "0" });
foreach (var c in _countryService.GetAllCountries(true))
model.AvailableCountries.Add(new SelectListItem() { Text = c.Name, Value = c.Id.ToString() });
PrepareAddressModel(model, address, false);
return View(model);
}
Am i doing something wrong?
How can i redirect from telerik grid- Edit Link to _CreateOrUpdateContact.cshtml page?
Please, check if "_CreateOrUpdateContact.cshtml" is in the same location with "EditContact.cshtml". I will suggest you to debug the code. Put a breakpoint at "public ActionResult EditContact(int id)" then check if debug point is hit after clicking the edit link from grid. If it is not hit then there may be some problem in route.
It would be better if you can provide the screen shot of the error you found
you can check the route here in the telerik-grid
columns.Bound(x => x.Id)
.Width(200)
.Centered()
.Template(x => Html.ActionLink(T("Admin.Common.Edit").Text, "Edit", new { id = x.Id }))
.ClientTemplate("" + T("Admin.Common.Edit").Text + "")
.Title(T("Admin.Common.Edit").Text);
as I think the route had a problem I should be like that
columns.Bound(x => x.Id)
.Width(200)
.Centered()
.Template(x => Html.ActionLink(T("Admin.Common.Edit").Text, "EditContact", new { id = x.Id }))
.ClientTemplate("" + T("Admin.Common.Edit").Text + "")
.Title(T("Admin.Common.Edit").Text);

Appending Default Value to dropdownlistfor - MVC 4 razor

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

ASP.net MVC3 howto edit sql database

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.

Categories