This is code snippet for load 15 text areas into an Add_New_Product form page.
public ActionResult Add_Product(int? page)
{
var dummyItems = db.AB_ProductTypeCategoryField;
var pager = new PaginationModel.Pager(dummyItems.Count(), page);
var model = new AddNewProduct
{
ListProductFields = dummyItems.OrderBy(i => i.ProductFieldID).Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList(),
Pager = pager
};
return View(model);
}
Since in this form page has many text areas(like 15) ,I limited with pagination , one text area per one page.
this is the view
I want use above ListProductFields data iteratvely inside same above method.
But once I insert the a value to first text area and then go to next text area , again if I click previous button , then first text area's added values are disappearing.
I decided to come up with sessions , So I changed above code as follows
Attempt 1:
public ActionResult Add_Product(int? page, AddNewProduct sample)
{
AddNewProduct newmodel = sample;
AddNewProduct newmodels = Session["TemplateData"] as AddNewProduct;
var dummyItems = db.AB_ProductTypeCategoryField;
var pager = new PaginationModel.Pager(dummyItems.Count(), page);
var model = new AddNewProduct
{
ListProductFields = dummyItems.OrderBy(i => i.ProductFieldID).Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList(),
Pager = pager
};
Session["TemplateData"] = model;
return View(model);
}
Edit
Attempt 2:
public ActionResult Add_Product(int? page, AddNewProduct sample)
{
TempData["AddNewProduct"] = sample;
AddNewProduct book = TempData["AddNewProduct"] as AddNewProduct;
var dummyItems = db.AB_ProductTypeCategoryField;
var pager = new PaginationModel.Pager(dummyItems.Count(), page);
var model = new AddNewProduct
{
ListProductFields = dummyItems.OrderBy(i => i.ProductFieldID).Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList(),
Pager = pager
};
sample = model;
return View(model);
}
But it doesn't keep any value
Related
I am using the bootstrap selectpicker for a multiselect dropdown menu to filter items of a table in a mvc5 web app. Everything works fine so far, but i am having trouble to keep the selected filters selected after submitting. So i can read the selected filters in the controller, but after that, there is only the first previously selected filter still shown as selected after the submit. I want all chosen filters to be still selected. How can I reach this?
Here ist my Code, the ViewModel contains:
public MultiSelectList AvailableUser_ID { get; set; }
private List<string> _selectedUserId = new List<string>();
public List<string> SelectedUserId
{
get { return _selectedUserId; }
set { _selectedUserId = value; }
}
The Controller (Post):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "SelectedUserId,SelectedUserInteractionTypesId")] IndexUserInteractionViewModel indexUserInteractionViewModel)
{
indexUserInteractionViewModel.UserInteractionViewModels = new List<UserInteractionViewModels>();
indexUserInteractionViewModel.AvailableUser_ID = new MultiSelectList(db.AspNetUsers.ToList(), "Id", "Email", indexUserInteractionViewModel.SelectedUserId);
// Filter Function: selectedUserId contains all the Ids of the previously selected filters
foreach (string selectedUserId in indexUserInteractionViewModel.SelectedUserId)
{
if (userInteraction.AspNetUsers_Id.Equals(selectedUserId))
// ...
}
}
And the View:
<script type="text/javascript">
$(document).ready(function () {
$('.selectpicker').selectpicker();
});
</script>
<th>#Html.DropDownListFor(Model => Model.SelectedUserId, Model.AvailableUser_ID as MultiSelectList, new { #id = "userFilter", #class = "selectpicker", #multiple = "mulitple", data_live_search = "true" })</th>
So how can I keep the Selection selected?
Unfortunately I have little js-knowledge and i am assuming that i could solve it in the js-script. I am hoping for some experts here. Thank you!
A colleague of mine found a solution, this is what works:
var selectedList = #Html.Raw(Json.Encode(Model.SelectedUserId));
if(selectedList.length > 0){
var result = '[';
for (i = 0; i < selectedList.length; i++) {
result += '"' + selectedList[i] + '",';
}
result = result.slice(0, -1); //remove last comma
result += ']';
$('.selectpicker').selectpicker('val', JSON.parse(result1));
}else{
$('.selectpicker').selectpicker();
}
connectionHelper.Select(query) returns datatable. I want to fill my dropdownlist in view with empList. How can I do it?
var query = "SELECT ADSOYAD, EMPLOYEE_NUMBER FROM TTF_PERSONEL";
var employeeNames = connectionHelper.Select(query);
var empList = new List<CalisanModels>();
var emp = new CalisanModels();
for (int i = 0; i < employeeNames.Rows.Count; i++)
{
var data = employeeNames.Rows[i];
emp.EmployeeNumber = Convert.ToInt32(data["EMPLOYEE_NUMBER"]);
emp.AdSoyad = data["ADSOYAD"].ToString();
empList.Add(emp);
}
So you have got your empList filled now you can send it to View where it can be rendered.
Set from your Action:
ViewBag.EmployeeList = empList;
Render in your view:
#Html.DropDownList("Employees", new SelectList((IEnumerable<MyMvcApp.CalisanModels>)ViewBag.EmployeeList, "EMPLOYEE_NUMBER", "ADSOYAD"))
Similar dropdown population in action I answered before here: https://dotnetfiddle.net/yPwHDB
I am working on MVC project where I have successfully created a search page with several dropdowns and textboxes. After the user queries the data, they are then transferred to a List page with a list of results corresponding to our search. I was wondering if it is possible to create a button located on the List view that returns them back to the search page, the search page's textboxes/dropdowns still populated with their previous search. Currently, when they return, their previous search was cleared, and they can't see what was queried.
Simplified: Is there a way to capture the data of a viewmodel on query submit, and then be able to access it with simple return button.
Get Method (populates dropdown etc)
[HttpGet]
public ActionResult Index()
{
//testTypes
var testTypesL = new List<string>();
var testTypesQr = from z in db.Results
orderby z.TestType
select z.TestType;
testTypesL.AddRange(testTypesQr.Distinct());
//technicians
var techniciansL = new List<string>();
var techniciansQr = from z in db.Results
orderby z.Technician
select z.Technician;
techniciansL.AddRange(techniciansQr.Distinct());
//engineers
var engineersL = new List<string>();
var engineerQr = from z in db.Results
orderby z.Engineer
select z.Engineer;
engineersL.AddRange(engineerQr.Distinct());
//testStalls
var testStallL = new List<string>();
var testStallQr = from z in db.Results
orderby z.TestStall
select z.TestStall;
testStallL.AddRange(testStallQr.Distinct());
//unit models
var unitModelL = new List<string>();
var unitModelQr = from z in db.Results
orderby z.UnitID
select z.UnitID;
unitModelL.AddRange(unitModelQr.Distinct());
TestDataViewModel obj = new TestDataViewModel();
obj.EngineerList = new SelectList(engineersL);
obj.TechnicianList = new SelectList(techniciansL);
obj.TestStallList = new SelectList(testStallL);
obj.UnitModelList = new SelectList(unitModelL);
obj.TestTypeList = new SelectList(testTypesL);
return View("Index", obj);
}
Post Method: (sends user query to the List view)
[HttpPost]
public ActionResult Index(TestDataViewModel obj)
{
var data = from d in db.Results
select d;
//search data parameters
if (!String.IsNullOrEmpty(obj.StartDate.ToString()) && !String.IsNullOrEmpty (obj.EndDate.ToString()))
{
data = data.Where(z => obj.StartDate <= z.EndDate && obj.EndDate >= z.EndDate);
}
if (!String.IsNullOrEmpty(obj.TestNumber.ToString()))
{
data = data.Where(z => z.TestNumber == obj.TestNumber);
}
if (!String.IsNullOrEmpty(obj.unitModel))
{
data = data.Where(z => z.UnitID == obj.unitModel);
}
if (!String.IsNullOrEmpty(obj.Project))
{
data = data.Where(z => z.ProjectNum.Contains(obj.Project));
}
if (!String.IsNullOrEmpty(obj.testType))
{
data = data.Where(z => z.TestType == obj.testType);
}
if (!String.IsNullOrEmpty(obj.engineer))
{
data = data.Where(z => z.Engineer == obj.engineer);
}
if (!String.IsNullOrEmpty(obj.technician))
{
data = data.Where(z => z.Technician == obj.technician);
}
if (!String.IsNullOrEmpty(obj.testStall))
{
data = data.Where(z => z.TestStall == obj.testStall);
}
return View("List", data);
}
I have a mvcjqgrid:
#(Html.Grid("dataGrid")
.SetJsonReader(new MvcJqGrid.DataReaders.JsonReader { Id = "Id", RepeatItems = false })
.SetRequestType(RequestType.Post)
.AddColumn(new Column("Name").SetLabel("Name").SetSearch(true))
.AddColumn(new Column("Email").SetLabel("E-Mail").SetSearch(true).SetFormatter(Formatters.Email))
.AddColumn(new Column("Phone").SetLabel("Phone").SetSearch(true))
.SetSearchToolbar(true)
.SetUrl(Url.Action("GetData", "Controller"))
.SetSearchOnEnter(false)
.SetRowNum(10)
.SetRowList(new[] { 10, 15, 20, 50 })
.SetViewRecords(true)
.SetPager("pager"))
and controller:
public ActionResult GetData()
{
return View(new myEntity[0]);
}
[HttpPost]
public JsonResult GetData(GridSettings gridSettings)
{
int totalRecords = DataHelper.GetCount();
var data = DataHelper.GetData(gridSettings);
var jsonData = new
{
total = totalRecords / gridSettings.PageSize + 1,
page = gridSettings.PageIndex,
records = totalRecords,
rows = data
};
return Json(jsonData);
}
EDIT:
so my question is how can i store GridSettings in session in right way, i need every time user backs to this page, page should be the same as when he left?
If i do:
Session["settings"] = gridSettings;
i need some way to compare stored gridSettings with the one passed to action.
Why don't you use the Http Cache for this case? We can write a caching provider, and Http Cache is one implementation for this. So in the future you can extend more providers for it.
The answer is to recreate Grid:
#{
var setting = Session["settings"] as GridSettings;
}
#(Html.Grid("dataGrid")
.SetJsonReader(new MvcJqGrid.DataReaders.JsonReader { Id = "Id", RepeatItems = false })
.SetRequestType(RequestType.Post)
.AddColumn(new Column("Name").SetLabel("Name").SetSearch(true))
.AddColumn(new Column("Email").SetLabel("E-Mail").SetSearch(true).SetFormatter(Formatters.Email))
.AddColumn(new Column("Phone").SetLabel("Phone").SetSearch(true))
.SetSearchToolbar(true)
.SetUrl(Url.Action("GetData", "Controller"))
.SetSearchOnEnter(false)
.SetRowNum(setting != null?setting.PageSize : 10)
.SetPage(setting != null?setting.PageIndex : 1);
.SetSortName(setting != null?setting.SortColumn : "");
.SetRowList(new[] { 10, 15, 20, 50 })
.SetViewRecords(true)
.SetPager("pager"))
I have a subject dropdownlist for a contact form. I always want the Other to be at the bottom of the list. The reason I ask this is because I created a controller so if I wanted to add more subjects I could do so. Anyways suggestions or ways I could go about making sure that the position of the Other subject is always on the bottom of the list?
public void PrepareSubjectCombo()
{
// Grab a list of subjects for the dialog box
IRepository<Subject> subjectRepository = new Repository<Subject>();
List<Subject> subjects = subjectRepository.GetAll().OrderBy(t => t.Position).ToList();
subjects.Insert(0, new Subject() { ID = 0, Name = "- Please Select -" });
ViewData["Subjects"] = subjects;
}
I have posted my combo box if this is of any help
You should simply use the proper overload of the DropDownList helper when rendering your dropdown in the view instead of trying to insert some dummy items into the collection:
public void PrepareSubjectCombo()
{
// Grab a list of subjects for the dialog box
IRepository<Subject> subjectRepository = new Repository<Subject>();
List<Subject> subjects = subjectRepository.GetAll().OrderBy(t => t.Position).ToList();
ViewData["Subjects"] = subjects;
}
and then in the view:
#Html.DropDownList(
"selectedSubject",
new SelectList(ViewData["Subjects"] as List<Subject>, "ID", "Name"),
"- Please Select -"
)
Now this being said, everytime I see someone using ViewData/ViewBag/ViewCrap instead of strongly typed views and view models I get sick and I feel myself into the obligation to show the correct way of doing this.
As always you start with a view model:
public class MyViewModel
{
public string SelectedSubject { get; set; }
public IEnumerable<SelectListItem> Subjects { get; set; }
}
then you have a controller action which will take care of populating this view model:
public ActionResult Index()
{
// TODO: You definitively don't want to hardcode your repository like this
// but use a constructor injection or this action will be impossible to unit test
IRepository<Subject> subjectRepository = new Repository<Subject>();
var subjects = subjectRepository.GetAll().OrderBy(t => t.Position).ToList();
var model = new MyViewModel
{
Subjects = subjects.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.Name
})
};
return View(model);
}
and finally in your strongly typed view:
#model MyViewModel
#Html.DropDownListFor(
x => x.SelectedSubject,
new SelectList(Model.Subjects, "Value", "Text"),
"- Please Select -"
)
DropDownList1.DataSource = YourDataSource;
DropDownList1.DataBind();
//Insert Other subject to the end
ListItem litem = new ListItem(" Other subject ", "value");
DropDownList1.Items.Insert(DropDownList1.Items.Count, litem);
Modify your code as shown below:
public void PrepareSubjectCombo()
{
// Grab a list of subjects for the dialog box
IRepository<Subject> subjectRepository = new Repository<Subject>();
List<Subject> subjects = subjectRepository.GetAll().OrderBy(t => t.Position).ToList();
subjects.Insert(0, new Subject() { ID = 0, Name = "- Please Select -" });
// Add this line
// Make sure you use the correct ID for the "Other" subject
subjects.Add(new Subject() { ID = 100, Name = "Other" });
// If you determine the ID based on the list, simply set the ID = subjects.Count + 1
int otherID = subjects.Count + 1;
subjects.Add(new Subject() { ID = otherID, Name = "Other" });
ViewData["Subjects"] = subjects;
}