How to use Postback in ASP.net MVC - html

How to preserve the selected value after postback for that dropdownlist?
I have used two dropdown lists in my application. I need to search the gridview data based on the selected values of dropdownlist. The searched data is displayed in the pagedlist format. But when i move to next page of pagedlist, its displaying the whole grid view data rather than searched data. so any help will be appreciated.
My Model
namespace CCIOfficeServiceManagementSystem.Models
{
public class AirtelManagementModel
{
public long MobileAcNumber { get; set; }
public long AirtelNumber { get; set; }
public int OneTime { get; set; }
public float MonthlyCharges { get; set; }
public float CallCharges { get; set; }
public float ValueAddedServices { get; set; }
public float MobileInternetUsage { get; set; }
public float Roaming{ get; set; }
public float Discounts { get; set; }
public float Taxes { get; set; }
public float TotalCharges { get; set; }
public string WhoUploaded { get; set; }
public DateTime UploadedDate { get; set; }
public DateTime DateOfCreation { get; set; }
public int ImportDateId { get; set; }
public List<MonthListClass> MonthList
{
get;
set;
}
public List<clsYearOfDate> YearList
{
get;
set;
}
}
public class MonthListClass
{
public int MonthSelectedId { get; set; }
public string MonthName { get; set; }
}
public class clsYearOfDate
{
public int YearSelectedId { get; set; }
public string YearOfDate { get; set; }
}
}
My View
#using (Html.BeginForm("ViewDataOfDatabase", "AirtelManagement",FormMethod.Post))
{
<h3>Search by PhoneNumber:#Html.TextBox("SearchString",ViewBag.CurrentFilter as string)</h3>
<p><h3>Year:#Html.DropDownList("Yearitems", (IEnumerable<SelectListItem>)ViewBag.SelectList, "Select Year")</h3>
<h3>Month:#Html.DropDownList("MonthItems", (IEnumerable<SelectListItem>)ViewBag.SelectMonthList, "Select Month")</h3>
<h3>City: #Html.DropDownList("CityNames", (IEnumerable<SelectListItem>)ViewBag.CityList, "Select City")</h3></p>
<p><input type="submit" value="Search" /></p>
<script>
$(document).ready(function () {
$("#Yearitems").change(function () {
//debugger;
//alert($("#Yearitems>option:selected").attr("Value"));
$.ajax({
type: "Post",
url: '#Url.Action("GetMonths","AirtelManagement")',
data: { YearId: $("#Yearitems>option:selected").attr("Value") },
datatype: "Json",
success: function (data) {
//debugger;
$("#MonthItems").html("");
$.each(data, function (index, item) {
$("#MonthItems").append(new Option(item.MonthName, item.MonthSelectedId));
});
},
error: function () {
alert("Select Year");
}
});
});
});
</script>
My controller's action Method
public ActionResult ViewDataOfDatabase(string sortorder, string currentFilter, string searchString, int? page,FormCollection collection)
{
CCIRepository _repository = CCIRepository.CreateRepository();
AirtelManagementModel _Airtelmodel = new AirtelManagementModel();
IEnumerable<CityListClass> CityList = _repository.GetCities();
IEnumerable<SelectListItem> CityListItems = from c in CityList
select new SelectListItem()
{
Value = c.CityName.ToString(),
Text = c.CityName.ToString(),
Selected = c.CityName == Request["CityNames"],
};
ViewBag.CityList = CityListItems;
IEnumerable<clsYearOfDate> SelectList = GetYears();
//IEnumerable<MonthListClass> SelectMonthList = GetMonths(YearId);
IEnumerable<SelectListItem> Yearitems = (from v in SelectList
select new SelectListItem()
{
Value = v.YearSelectedId.ToString(),
Text = v.YearOfDate.ToString(),
Selected = v.YearOfDate == Request["Yearitems"],
});
ViewBag.SelectList = Yearitems;
int DateId=0;
string CityName = string.Empty;
try
{
int SelectedYear = Convert.ToInt16(collection["Yearitems"].ToString());
int SelectedMonth = Convert.ToInt16(collection["MonthItems"].ToString());
CityName = collection["CityNames"].ToString();
DateId = _repository.GetImportDateId(SelectedYear, SelectedMonth);
}
catch(NullReferenceException Ex)
{
}
//IEnumerable<SelectListItem> MonthItems = (from m in SelectMonthList
// select new SelectListItem()
// {
// Value = m.MonthSelectedId.ToString(),
// Text = m.MonthName,
// });
//ViewBag.SelectMonthList = MonthItems;
IEnumerable<SelectListItem> MonthItems = Enumerable.Empty<SelectListItem>();
ViewBag.SelectMonthList = MonthItems;
List<AirtelManagementModel> list = ViewDetails();
ViewBag.CurrentSort = sortorder;
ViewBag.PhoneSortParm = String.IsNullOrEmpty(sortorder) ? "Phone_desc" : "";
if (searchString != null )
{
page = 1;
}
else
{
searchString = currentFilter;
}
//if(searchString!=null)
//{
ViewBag.CurrentFilter = searchString;
var airteldetails = from _model in list
select _model;
if(!String.IsNullOrEmpty(searchString) && DateId!=0 && !String.IsNullOrEmpty(CityName))
{
airteldetails = _repository.FilterAirtelDetails(searchString, DateId, CityName);
int PageSize = 5;
int PageNumber = (page ?? 1);
return View(airteldetails.ToPagedList(PageNumber, PageSize));
}
//airteldetails=airteldetails.OrderByDescending(A=>A.AirtelNumber);
int pageSize = 5;
int pageNumber = (page ?? 1);
//return View(airteldetails.ToList());
return View(airteldetails.ToPagedList(pageNumber, pageSize));
//}
//if (list.Count > 0)
//{
// var airteldetails = from _model in list
// select _model;
// return View(airteldetails.ToPagedList(pageNumber,pageSize));
//}
//else
//{
// ModelState.AddModelError("Error", "No Data found in Database");
// return RedirectToAction("ImportExcelFile", "AirtelManagement");
//}
}

Related

how to join table and retrieve necessary columns

we are working on api creation using asp.net core web api and mysql as backend. i need to maintain this architecture and and also need to join table. i have tried many ways still stuck in middle.
public class CallLogs:AuditableEntity
{
public int CallTypeId { get; set; }
public virtual CallType CallType { get; set; }
public virtual ICollection<CallType> CallTypes { get; set; }
public int PatientId { get; set; }
public int AgentId { get; set; }
public string CallDuration { get; set; }
public DateTime Date { get; set; }
public int ServiceId { get; set; }
public string Message { get; set; }
//public virtual Patient Patient { get; set; }
//public virtual Service Service { get; set; }
}
this calllogs has many tables foreign key and i want to retrieve some columns from each table. so how should i retrieve? in this project we added mapper classes and response and request classes
public class CallType:AuditableEntity
{
public string Name { get; set; }
public virtual ICollection<CallLogs> CallLogs { get; set; }
}
and made service where i including the tables
private ISpecification<CallLogs> GetSpecification(Expression<Func<CallLogs, bool>>
expression = null, string sortField = "none", int sortOrder = -1)
{
if (expression == null)
expression = v => v.IsDeleted != true;
Infrastructure.Specifications.BaseSpecification<CallLogs> specification =
new
Infrastructure.Specifications.BaseSpecification<CallLogs>(expression);
//specification.IncludeExp = p => p.Include(x => x.Patient);
specification.IncludeExp = p => p.Include(x => x.CallType);
// specification.IncludeExp = p => p.Include(x => x.Service);
if (sortField != "none" && !string.IsNullOrEmpty(sortField))
specification.OrderByDescending = p => p.GetSortOrder(sortField,
sortOrder);
else
specification.OrderByDescending = p => p.OrderByDescending(p =>
p.IsActive)
.ThenByDescending(p => p.CreatedDate)
.ThenByDescending(p => p.Id);
specification.IsPagingEnabled = true;
specification.Skip = (pageNo - 1) * pageSize;
specification.Take = pageSize;
return specification;
}
and we are calling this function in the getall api
public async Task<EntityResponseModel> GetAllAsync(int pageNo = 1, int pageSize = 10)
{
var callLogsResponse = new List<CallLogsResponse>();
this.pageNo = pageNo;
this.pageSize = pageSize;
var callLogs = (await repository.FindAsync(GetSpecification())).ToList();
// .Select(s => new
// {
// Name = s.CallType.Name,
// PateintId = s.PatientId,
// AgentId = s.AgentId,
// CallDuration = s.CallDuration,
// Date = s.Date,
// ServiceId = s.ServiceId,
// Message = s.Message,
// Id = s.Id,
// IsActive = s.IsActive
// }).ToList() ;
int count = await repository.CountAsync(v => !v.IsDeleted);
var _pages = Math.Round(count / (double)pageSize,
MidpointRounding.ToPositiveInfinity);
var statusCode = 200;
callLogsResponse = _mapper.Map<List<CallLogs>, List<CallLogsResponse>>
(callLogs);
return new EntityResponseModel
{
APIResponse =
APIResponseHelper.Getinstance().ConvertToAPIResponse(callLogsResponse,
string.Empty,statusCode, Convert.ToInt32(_pages),
Convert.ToInt32(count)),
Entity = callLogs,
EntityResponse = callLogsResponse
};
}
how do i join table and column what i need?

How make dropdownlist to access data on your SelectItemList using asp.net mvc?

I am using DropDownlist in order to get country of all the world. I have attached the file(country_list.txt) using srcFilePath. The error i am getting is "There is no ViewData item of type 'IEnumerable' that has the key 'SelectedCountryId'.What could be an issue, because my EditFormTrainingRegViewModel does have this field SelectedCountry as a primary key. Its been declared as public int? SelectedCountryId {get;set;}
// List for countries.
private IEnumerable<SelectListItem> GetCountryList()
{
SelectList listcn = null;
try
{
var list = this.LoadData().Select(p => new SelectListItem
{
Value = p.Country_Id.ToString(),
Text = p.Country_Name
});
listcn = new SelectList(list, "Value", "Text");
}catch(Exception ex)
{
throw ex;
}
return listcn;
}
public ActionResult DropDownSelect()
{
EditTrainingRegFormViewModel model = new EditTrainingRegFormViewModel();
model.SelectedCountryId = 0;
this.ViewBag.CountryList = this.GetCountryList();
return this. View(model);
}
// Loading data for country list.
private List<EditTrainingRegFormViewModel> LoadData()
{
List<EditTrainingRegFormViewModel> lst = new List<EditTrainingRegFormViewModel>();
try
{
string line = string.Empty;
string srcFilePath = "Content/files/country_list.txt";
var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
var fullPath = Path.Combine(rootPath, srcFilePath);
string filePath = new Uri(fullPath).LocalPath;
StreamReader src = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));
// while to read the file
while((line = src.ReadLine()) !=null) {
EditTrainingRegFormViewModel infoLst = new EditTrainingRegFormViewModel();
string[] info = line.Split(',');
//Setting
infoLst.Country_Id = Convert.ToInt32(info[0].ToString());
infoLst.Country_Name = info[1].ToString();
lst.Add(infoLst);
}
src.Dispose();
src.Close();
}catch(Exception ex)
{
Console.Write(ex);
}
return lst;
}
//View
#Html.DropDownListFor(m=>m.SelectedCountryId, this.ViewBag.CountryList as SelectList, new {#class = "form-control"})
// Model class
public class EditTrainingRegFormViewModel
{
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Position { get; set; }
public string Company { get; set; }
public string Address { get; set; }
[Display(Name = "Choose country")]
public int ? SelectedCountryId { get; set; }
public string Code { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Cell_Number { get; set; }
public List<string> Dietary_requirement { get; set; }
public string Email { get; set; }
public int Country_Id { get; set; }
public string Country_Name { get; set; }
}

How to create multiple Radiobutton group in ASP.Net Core 2 and Razor?

I want to create multiple grouped Radio buttons. So, basically I have multiple questions and 3 radio buttons with answers. The problem I'm facing is how to return the selected value for the multiple radio buttons.
Controller
public IActionResult Test()
{
SafetyObservationCardForm form = new SafetyObservationCardForm();
using (IDbConnection dbConnection = Connection)
{
dbConnection.Open();
var questions = dbConnection.Query<QuestionsViewModel>("SELECT * FROM SOCQuestions ORDER BY soc_order_id");
var observationType = new List<ObservationType>
{
new ObservationType { Id = 1, Name = "Safe" },
new ObservationType { Id = 2, Name = "At Risk" },
new ObservationType { Id = 3, Name = "N/A" }
};
var rb = new List<Answer>();
foreach (var item in questions)
{
rb.Add(new Answer { Id = item.soc_question_id, ObservationTypes = observationType });
};
form.Answers = rb;
form.Questions = questions.ToList();
return View(form);
}
}
Model
public class SafetyObservationCardForm
{
public List<QuestionsViewModel> Questions { get; set; }
public string Comments { get; set; }
public string Location { get; set; }
public string Observer { get; set; }
public DateTime TimeStamp { get; set; }
public string Task { get; set; }
public ObserverType ObserverType { get; set; }
public IEnumerable<Answer> Answers { get; set; }
}
public class ObserverType
{
public bool Supervisor { get; set; }
public bool Peer { get; set; }
public bool Self { get; set; }
public bool Other { get; set; }
}
public class ObservationType
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Answer
{
public int Id { get; set; }
public IEnumerable<ObservationType> ObservationTypes { get; set; }
public int SelectedObservation { get; set; }
}
}
View
Here I'm trying the loop. Answers model is null when I submit the form for some reason.
#model DBI.Safety.Models.SafetyObservationCardForm
<form asp-action="CreateTest">
#foreach (var answer in Model.Answers)
{
<input name="#answer.Id" asp-for="#answer.SelectedObservation" type="radio"
value="#answer.Id" /> #answer.ObservationTypes
}
</form>

When a user selects an item from dropdown list then that item must be removed for that user in mvc 4

I am creating a user course project for learning MVC 4. In this project, when a user logs in they can see their courses and other details. A user can create or edit the courses. So I am displaying list of courses in dropdown list during create and edit. What I want is, when a user selects a course and it is added to his list of courses then that course should not be displayed in the dropdown list for that user. Some code for create is given below:
CourseController:
public ActionResult Create()
{
User user = (User)Session["User"];
var usr = db.Users.Find(user.UserId);
if (Session["User"] != null)
{
ViewBag.CourseId = new SelectList(db.Courses, "CourseId", "CourseName");
ViewBag.UserId = usr.UserId;
ViewBag.FirstName = usr.FirstName;
}
return View();
}
//
// POST: /Course/Create
[HttpPost]
public ActionResult Create(UserCourse usercourse)
{
User user = (User)Session["User"];
var usr = db.Users.Find(user.UserId);
if (Session["User"] != null)
{
if (ModelState.IsValid)
{
db.UserCourses.Add(usercourse);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CourseId = new SelectList(db.Courses, "CourseId", "CourseName", usercourse.CourseId);
ViewBag.UserId = usr.UserId;//from c in db.Users.Where(u => u.UserId == usercourse.UserId) select c;
ViewBag.FirstName = usr.FirstName;
return View();
}
return View(usercourse);
}
Create.cshtml:
<div class="editor-label">
#Html.DisplayNameFor(model => model.CourseId)
</div>
<div class="editor-field">
#Html.DropDownList("CourseId", String.Empty)
#Html.ValidationMessageFor(model => model.CourseId)
</div>
<p>
<input type="submit" value="Create" />
</p>
Model class for User:
public partial class User
{
public User()
{
this.UserCourses = new HashSet<UserCourse>();
}
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Required(ErrorMessage = "Please Provide User Name", AllowEmptyStrings = false)]
public string UserName { get; set; }
[Required(ErrorMessage = "Please Provide Password", AllowEmptyStrings = false)]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
public string Password { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Email { get; set; }
public string PhoneNo { get; set; }
public virtual ICollection<UserCourse> UserCourses { get; set; }
}
Model class for Course:
public partial class Course
{
public Course()
{
this.UserCourses = new HashSet<UserCourse>();
}
public int CourseId { get; set; }
public string CourseName { get; set; }
public virtual ICollection<UserCourse> UserCourses { get; set; }
}
Model class for UserCourse:
public partial class UserCourse
{
public int Id { get; set; }
public Nullable<int> UserId { get; set; }
public Nullable<int> CourseId { get; set; }
public virtual Course Course { get; set; }
public virtual User User { get; set; }
}
Please reply.
[EDITED]: Try it this way:
public ActionResult Create()
{
User user = (User)Session["User"];
var usr = db.Users.Find(user.UserId);
if (Session["User"] != null)
{
var courses = db.Courses.Where(x=>!x.UserCourses.Any(y=>y.CourseId == x.CourseId && y.UserId == usr.UserId)).ToList();
ViewBag.CourseId = new SelectList(courses , "CourseId", "CourseName");
ViewBag.UserId = usr.UserId;
ViewBag.FirstName = usr.FirstName;
}
return View();
}
//
// POST: /Course/Create
[HttpPost]
public ActionResult Create(UserCourse usercourse)
{
User user = (User)Session["User"];
var usr = db.Users.Find(user.UserId);
if (Session["User"] != null)
{
if (ModelState.IsValid)
{
db.UserCourses.Add(usercourse);
db.SaveChanges();
return RedirectToAction("Index");
}
var courses = db.Courses.Where(x=>!x.UserCourses.Any(y=>y.CourseId == x.CourseId && y.UserId == usr.UserId)).ToList();
ViewBag.CourseId = new SelectList(courses, "CourseId", "CourseName", usercourse.CourseId);
ViewBag.UserId = usr.UserId;//from c in db.Users.Where(u => u.UserId == usercourse.UserId) select c;
ViewBag.FirstName = usr.FirstName;
return View();
}
return View(usercourse);
}

Passsing a array in json and accessing it in controller of mvc

i am trying to make a array marklistdetails to post the mutliple students details, i am not able to access the same on controller, which is giving error as object not initialised
json code
var MarksEntry = {
Adm_Or_Name: '',
AdmissionNo: '',
Name: '',
ClassId: '',
ClassSectionId: '',
RollNo: '',
MarksEntered: '',
RemarksEntered: '',
Subjectid: '',
ExaminationID: '',
ExamDate: '',
Present: '',
MarksEntryDetails: [],
};
var MarksEntryDetails =
{
// StudentId: '',
MarksEntered: '',
// RemarksEntered: '',
// Total_Oral_Marks: '',
// TOTAL_PRACTICAL_MARKS: '',
//TOTAL_PROJECT_MARKS: '',
//TOTAL_MARKS: '',
// PRESENT: '',
// PASS_FAIL: '',
};
function SavingRecords(url) {
var result = 0;
var Index = 0;
//var marksEntrylist = [];
MarksEntry.ClassSectionId = $("table#IntialDetails tr").find("td").eq(6).html()
MarksEntry.ExaminationID = $("table#IntialDetails tr").find("td").eq(7).html()
MarksEntry.Subjectid = $("table#IntialDetails tr").find("td").eq(8).html()
$('table#student_marks tr').each(function () {
MarksEntry.MarksEntryDetails.add(new CreateMarksEntry(this));
console.log(MarksEntry.MarksEntryDetails);
$.getJSON(url,JSON.stringify(MarksEntry), function (data) {
Success = data;
});
// return Success
// alert(marksEntrylist);
//Index = $(this).index() + 1;
// MarksEntry.ExamDate = Formateddate;
// result = result + CreateMarksEntry(this);
});
if (result > 0) {
$("#Complete").html("No.of Records saved:" + result);
$("#Complete").dialog({
resizable: false,
height: 140,
modal: true,
autoOpen: true,
buttons: {
'Done': function () {
$(this).dialog('close');
var url = $("#RedirectTo").val();
location.href = url;
}
}
});
}
else {
alert('Records havent been saved');
}
function CreateMarksEntry(objTr) {
var cols = $(objTr).find('td');
// this.Name = $(cols[0]).html();
if ($(cols[4]).html() == " ") {
this.MarksEntered = "";
}
if ($(cols[5]).html() == " ") {
this.RemarksEntered = "";
}
var Details={
//this.RollNo = $(cols[1]).html();
//this.AdmissionNo = $(cols[2]).html();
MarksEntered: $(cols[4]).html(),
remarksentered: $(cols[5]).html()
}
// this.RemarksEntered = $(cols[5]).html();
// if (this.Name == " ") {
// this.Name = "";
// }
// if (this.RollNo == " ") {
// this.RollNo = "";
// }
// if (this.AdmissionNo == " ") {
/// this.AdmissionNo = "";
// }
if (this.MarksEntered == " ") {
this.MarksEntered = "";
}
if (this.RemarksEntered == " ") {
this.RemarksEntered = "";
}
// $.getJSON(url, MarksEntry, function (data) {
// Success = data;
// });
// return Success
};
}
model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Examination.Domain.ViewModel
{
public class vmStudentMarks
{
public string ExamTypeDesc { get; set; }
public int Subjectid { get; set; }
public int ClassSectionID { get; set; }
public string ExamDate { get; set; }
public int ExaminationID { get; set; }
public int Id { get; set; }
public string SchoolId { get; set; }
public string SessionId { get; set; }
public string Name { get; set; }
public string AdmissionNo { get; set; }
public string RollNo { get; set; }
public string Written { get; set; }
public string Oral { get; set; }
public string Practical { get; set; }
public string PASS_FAIL { get; set; }
public string Project { get; set; }
public string RemarksEntered { get; set; }
public string MarksEntered { get; set; }
public string ClassSection { get; set; }
public string SubjectName { get; set; }
public string StudentId { get; set; }
public long EXAM_RESULT_ID{ get; set; }
public long EXAM_RESULT_DET_ID { get; set; }
public int MAX_MARKS { get; set; }
public bool Present { get; set; }
public int ENTRY_USER_ID { get; set; }
public int UPDATE_USER_ID { get; set; }
public int GRACE { get; set; }
//public MarksEntryDetails[] #List { get; set; }
public List<MarksEntryDetails> MarksEntryDetails { get; set; }
}
public class MarksEntryDetails
{
public string StudentId { get; set; }
public string MarksEntered { get; set; }
public string remarksentered { get; set; }
public int total_oral_marks { get; set; }
public int total_practical_marks { get; set; }
public int total_project_marks { get; set; }
public int total_marks { get; set; }
public int present { get; set; }
public string pass_fail { get; set; }
public int grace { get; set; }
}
}
controller
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult CreateRecords(vmStudentMarks MarksEntry)
{
MarksEntry.MarksEntryDetails[0].MarksEntered.ToString();//error throws as object not intialised
UserProfile userProfile = SchoolSession.CurrentUser;
int Sucess = examScoreService.PostMARKSENTRYDETAILS(userProfile.School.Id, userProfile.CurrentSession.Id,
userProfile.EmployeeId,MarksEntry);
return Json(Sucess, JsonRequestBehavior.AllowGet);
}
You can use JSON.stringify when you posting data to pass arry of objects to controller.
$.ajax(
{
url: 'controller/CreateRecords',
data: JSON.stringify({MarksEntry: MarksEntry}),
contentType: 'application/json',
dataType: 'json',
type: 'POST',
success: function (data) {
// success
},
error: function () {
// error
}
});
Please refer following post for more information.
Pass Complex JavaScript Object to MVC Controller
It illustrates how we can pass complex javascript objects to MVC controller.
Thanks !