I'm in a bit of a pickle rick and I need some help. Below is the code for my select lists in a form. I need the certification list to populate based off of what category they pick from the category list. How do I get this to work?
CODE:
// GET: INT_CertificationsXREF/Create
public IActionResult Create()
{
ViewBag.FullName = UserInformation.Globals.FullName;
ViewData["INT_CertificationCategoriesID"] = new SelectList(_context.INT_CertificationCategories, "ID", "Category");
ViewData["INT_CertificationConferredID"] = new SelectList(_context.INT_CertificationConferred, "ID", "ConferredBy");
ViewData["INT_CertificationsID"] = new SelectList(_context.INT_Certifications, "ID", "Certification").Where(i => i.CategoryID = ViewData["INT_CertificationCategoriesID"]);
ViewData["RIM_ResourceID"] = new SelectList(_context.RIM_Resource, "ID", "FirstName");
return View();
}
you can filter the list A with the list B using the function Contains
ViewData["INT_CertificationCategoriesID"] = new SelectList(_context.INT_CertificationCategories, "ID", "Category");
ViewData["INT_CertificationConferredID"] = new SelectList(_context.INT_CertificationConferred, "ID", "ConferredBy");
ViewData["INT_CertificationsID"] = new SelectList(_context.INT_Certifications, "ID", "Certification").Where(i => i.CategoryID.Contains(_context.INT_CertificationCategories.ID));
ViewData["RIM_ResourceID"] = new SelectList(_context.RIM_Resource, "ID", "FirstName");
Related
My viewbag is showing values correctly at the view, but when the creation control is called the values are null, so since these values are foreign keys in another table, I get an exception:
SqlException: The INSERT statement conflicted with the FOREIGN KEY >constraint "FK_dbo.INFO_APONTAMENTO_dbo.BARCO_Barco_Id". The conflict >occurred in database "RVEIO", table "dbo.BARCO", column 'Id'.
Here is the code:
public ActionResult Create()
{
ViewBag.SubCodigos = new SelectList(_subCodigosOperacionaisRepository.GetAll(), "Id", "Codigo");
ViewBag.Codigos = new SelectList(_codigosOperacionaisService.GetAll(), "Id", "Codigo");
ViewBag.LocalDaOperacao = new SelectList(_localDaOperacaoAppService.GetAll(), "Id", "Nome");
ViewBag.Barcos = new SelectList(_barcoRepository.GetAll(), "Id", "Nome");
return View();
}
[HttpPost]
public ActionResult Create(ApontamentoViewModel apontamentoViewModel)
{
if (!ModelState.IsValid)
{
return View(apontamentoViewModel);
}
ViewBag.Codigos = new SelectList(_codigosOperacionaisService.GetAll(), "Id", "Codigo", apontamentoViewModel.InfoApontamento.CodigosDeOperacao_Id);
ViewBag.SubCodigos = new SelectList(_subCodigosOperacionaisRepository.GetAll(), "Id", "Codigo", apontamentoViewModel.InfoApontamento.SubCodigosDeOperacao_Id);
ViewBag.LocalDaOperacao = new SelectList(_localDaOperacaoAppService.GetAll(), "Id", "Nome", apontamentoViewModel.InfoApontamento.LocalDaOperacao_Id);
ViewBag.Barcos = new SelectList(_barcoRepository.GetAll(), "Id", "Nome", apontamentoViewModel.InfoApontamento.Barco_Id);
var apontamento = _apontamentoAppService.Add(apontamentoViewModel);
}
When the
var apontamento = _apontamentoAppService.Add(apontamentoViewModel);is called, the value comes null
My View:
<div class="col-md-10">
#Html.DropDownList("Codigos", String.Empty)
#Html.DropDownList("SubCodigos", String.Empty)
#Html.DropDownList("LocalDaOperacao", String.Empty)
#Html.DropDownList("Barcos", String.Empty)
</div>
I have a static dropdownlist and editor need to take the selected value from the dropdownlist and the written value from the editor and make a concatenation between the two values and save it in a Database table column in the post ActionResult:
This is the View:
#Html.DropDownList("Term.Description", new List<SelectListItem>
{
new SelectListItem{ Text="Winter", Value = "Winter-" },
new SelectListItem{ Text="Spring", Value = "Spring-" },
new SelectListItem{ Text="Fall", Value = "Fall-" },
new SelectListItem{ Text="Summer", Value = "Summer-" }
}, new { #class = "description-text" })
#Html.Editor("TermYear","", new { htmlAttributes = new { #class = "description-text", placeholder = "2018", data_placeholder = " " } })
ActionResult:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Term term, int[] applicantTypes)
{
ModelState.Remove("ApplicantTypes");
if (ModelState.IsValid)
{
if (applicantTypes != null && applicantTypes.Length > 0)
{
foreach (var item in applicantTypes)
{
term.ApplicantTypes.Add(db.ApplicantTypes.FirstOrDefault(x => x.ApplicantTypeID == item));
}
}
db.Terms.Add(term);
db.Configuration.ValidateOnSaveEnabled = false;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ApplicantTypes = new MultiSelectList(db.ApplicantTypes, "ApplicantTypeID", "Name", term.ApplicantTypes.Select(x => x.ApplicantTypeID));
return View(term);
}
Finally, I need the `Term.Description = DropDownListSelectedValue-EditorValue'
In my view I have:
<tr class="form-group">
<th><label class="control-label">Technician</label></th>
<td>
#Html.DropDownListFor(model => model.UserID, (IEnumerable<SelectListItem>)ViewBag.TechnicianID)
#Html.ValidationMessageFor(model => model.UserID)
</td>
</tr>
And in my controller:
public ActionResult Edit(int? id) {
var salescall = (id != null) ? db.SalesCalls.Find(id) : new SalesCall();
if (salescall == null) {
return HttpNotFound();
}
ViewBag.CompanyID = new SelectList(db.Companies, "CompanyID", "Name", salescall.CompanyID);
var technicians = db.UserProfiles.Select(t => new {
ID = t.ID,
Name = t.FirstName + " " + t.LastName,
}).OrderBy(t => t.Name);
var techID = CurrentUser.UserID(User);
ViewBag.TechnicianID = new SelectList(technicians, "ID", "Name", techID);
return View(salescall);
}
When I debug, the value being passed to techID is the correct value, and that value does exist in the dropdown, but for some reason it is not being selected. How can I make this work?
Change
ID = t.ID,
new SelectList(technicians, "ID", "Name", techID);
To
Id = t.ID,
new SelectList(technicians, "Id", "Name", techID);
My hunch is you are defining Id in the User model. It should have Id and Name.
EDIT
If techID is an integer, make sure you pass in an anonymous object:
new SelectList(technicians, "Id", "Name", new { Id = techID });
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.
I have this code
List<SelectListItem> list = new List<SelectListItem>()
{
new SelectListItem() { Text = "bob", Value = "bob"},
new SelectListItem() { Text = "apple", Value = "apple"},
new SelectListItem() { Text = "grapes", Value = "grapes"},
};
This will be used for binding with the asp.net mvc html helper. However I want to sort it before I bind it. How could i do this?
If you can use LINQ then:
list.OrderBy(x => x.Value)
or
list.OrderByDescending(x =>x.Value)
should do it.
edit
That should read;
list = list.OrderBy(x => x.Value);
Here you go:
List<SelectListItem> list = new List<SelectListItem>()
{
new SelectListItem() { Text = "apple", Value = "apple"},
new SelectListItem() { Text = "bob", Value = "bob"},
new SelectListItem() { Text = "grapes", Value = "grapes"},
};
Sorted:)
Sorry, couldn't stop myself:)
EDIT
It looks as if you needed:
var fruits = new List<string> {"apple", "bob", "grapes"};
fruits.Sort();
var fruitsSelectList = new SelectList(fruits);
and then in view
Html.DropDownList("Fruit",fruitsSelectList);
var sorted = (from li in list
orderby li.Text
select li).ToList();
Voila!!
Isn't the idea of MVC to separate function and display? What if you want to reuse the same list with different orderings?
I'd have thought this would be best as it only sorts if for the specified control.
Add a property to the Model you are using for the view:
public SelectList Fruit { get; set; }
Populate that list in your constructor (I'm using Entity Framework):
model.Fruit= new SelectList(db.tblFruit.Select(f => new { Id = f.ID, Name = f.Name }), "ID", "Name", "[Select Fruit]");
Then add your select list:
#Html.DropDownListFor(x => x.ID, new SelectList(Model.Fruit.OrderBy(y => y.Text), "Value", "Text"), "-- Select One --", new { #class = "form-control" })
you can also sort it in the client side using javascript (jquery)
BTW if you know the elements of the list just sort them yourself :
List<SelectListItem> list = new List<SelectListItem> {
new SelectListItem { Text = "apple", Value = "apple"},
new SelectListItem { Text = "bob", Value = "bob"},
new SelectListItem { Text = "grapes", Value = "grapes"}
};
A very simple way to handle it in Controller:
ViewBag.change_week = new SelectList(db.weeks.OrderBy(x=> x.week_guid), "week_guid", "week_number");
list.Sort
List<SelectListItem> list = new List<SelectListItem>()
{ new SelectListItem() { Text = "bob", Value = "bob"},
new SelectListItem() { Text = "apple", Value = "apple"},
new SelectListItem() { Text = "grapes", Value = "grapes"}, };
list.sort;
-------Store Procedure-----(SQL)
USE [Your Database]
GO
CRATE PROC [dbo].[GetAllDataByID]
#ID int
AS
BEGIN
SELECT * FROM Your_Table
WHERE ID=#ID
ORDER BY Your_ColumnName
END
----------Default.aspx---------
<asp:DropDownList ID="ddlYourTable" runat="server"></asp:DropDownList>
---------Default.aspx.cs-------
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<YourTable> table= new List<YourTable>();
YourtableRepository tableRepo = new YourtableRepository();
int conuntryInfoID=1;
table= tableRepo.GetAllDataByID(ID);
ddlYourTable.DataSource = stateInfo;
ddlYourTable.DataTextField = "Your_ColumnName";
ddlYourTable.DataValueField = "ID";
ddlYourTable.DataBind();
}
}
-------LINQ Helper Class----
public class TableRepository
{
string connstr;
public TableRepository()
{
connstr = Settings.Default.YourTableConnectionString.ToString();
}
public List<YourTable> GetAllDataByID(int ID)
{
List<YourTable> table= new List<YourTable>();
using (YourTableDBDataContext dc = new YourTableDBDataContext ())
{
table= dc.GetAllDataByID(CID).ToList();
}
return table;
}
}