dropdownlist not showing data properly - javascript

i have this dropdown list which get the data from db but does not display the data properly n the view
The codes are as follows:
View:
#Html.DropDownListFor(m=> Model.SystemRAteModel.Role, new SelectList(Model.SystemRAteModel.GetRole.Items),"Value","Text")
Model:
public class SystemRolesModel
{
public static RoleProvider Provider { get; internal set; }
public int ID { get; set; }
public String Role { get; set; }
public Boolean Status { get; set; }
public SelectList GetRole { get; set; }
}
Controller
public ActionResult Index()
{
IApplicationLogic app = new ApplicationLogic(session);
RateManagementModel RTM = new RateManagementModel();
var value = app.GetVatValue();
var freight = app.GetFreightValue();
// var systemrolemodel = new SystemRolesModel();
//var currency = new List<SelectList>();
// currency= app.GetListOfRoles();
//IList<string> ERModel = new List<string>();
//foreach (var _currency in currency)
//{
// var curent = _currency.ToString();
// ERModel.Add(curent);
//}
var sysmodel = new SystemRolesModel();
sysmodel.GetRole = getRoleSelectList();
RTM.SystemRAteModel = sysmodel;
ViewData["ViewVatValue"] = value;
//ViewData["ViewCurrency"] = new SelectList(currency);
//ViewBag.LocationList = freight;
ViewData["ViewFreightValue"] = freight;
return View("Index",RTM);
}
public SelectList getRoleSelectList()
{
IApplicationLogic app = new ApplicationLogic(session);
var roles = app.GetListOfRoles();
SystemRoles sr = new SystemRoles();
sr.Id = -1;
sr.Role = "--select role--";
roles.Add(sr);
IEnumerable<SystemRoles> sortedRoles = roles.OrderBy(d => d.Id);
IList<SystemRoles> _sortedRoles = sortedRoles.ToList();
return new SelectList(_sortedRoles, "Id", "Role");
}
i have tried everything on the net but cant get a hand on it. Please any help will do.OutPut of my System At the moment

You don't need to create a new SelectList again in View, as you are already creating that in controller side and passing it via Model, you should be able to directly use it in View like:
#Html.DropDownListFor(m=> Model.SystemRAteModel.Role,Model.SystemRAteModel.GetRole)
This should populate the dropdown with the values, but it would display same values for all the items for now, as your code is setting hard-coded same values for all properties here:
SystemRoles sr = new SystemRoles();
sr.Id = -1;
sr.Role = "--select role--";
roles.Add(sr);
You would need to change it to have proper values.
Another easy way can be to use the constructor of SelectList this way:
public SelectList getRoleSelectList()
{
IApplicationLogic app = new ApplicationLogic(session);
var roles = app.GetListOfRoles().OrderBy(x=> x.RoleID);
return new SelectList(roles.ToList(), "RoleID", "Role");
}
you will just need to replace RoldID and Role property name with the proerty names you have in the DTO.
Hope it helps.

See this example:
#Html.DropDownList("Name", Model.Select(modelItem => new SelectListItem
{
Text = modelItem.Name,
Value = modelItem.Id.ToString(),
Selected = modelItem.Id == "12314124"
}))

Related

How can I convert javascript var obj = {}; to C#?

I have the following javascript code:
var key = "Mykey" + NextNumber.toString();
var value = {"Name":"Tony","Width":"150","Height":"320"};
var valuejson = JSON.stringify(value);
var obj = {};
obj[key] = valuejson
I know how to create valuejson in C#, but I don't know how to create something similar like var obj = {}; in C#. How can I do that in C#?
key and valuejson in C#:
public class MyValue
{
public string Name { get; set; }
public string Width { get; set; }
public string Height { get; set; }
}
MyValue value = new MyValue();
value.Name = "Tony";
value.Width = "150";
value.Height = "320";
string jsonValue = JsonConvert.SerializeObject(value);
string key = "Mykey" + NextNumber.toString();
You could try to use a dynamic object which works similar to {} in javascript... But... You have to be CAREFUL, example:
public class test
{
public class MyValue
{
public string Name { get; set; }
public string Width { get; set; }
public string Height { get; set; }
}
public void testing()
{
MyValue value = new MyValue();
value.Name = "Tony";
value.Width = "150";
value.Height = "320";
dynamic jsonValue = new { keyA = value };
string height = jsonValue.keyA.Height;
}
}
EDI:
Actually, I read a bit more carefully your need, and a dictionary can also suit your needs:
public class test
{
public class MyValue
{
public string Name { get; set; }
public string Width { get; set; }
public string Height { get; set; }
}
Dictionary<string, MyValue> dic = new Dictionary<string, MyValue>();
public void testing()
{
string key = "Mykey" + NextNumber.toString();
MyValue value = new MyValue();
value.Name = "Tony";
value.Width = "150";
value.Height = "320";
dic.Add(key, value);
}
}
Since you where asking for the equivalent of a var x = {} I suggested the dynamic but I see you want to create a key and associate that value to that key.
If you're looking for an object whose members can be dynamically added and removed at run time (like in Javascript) then the ExpandoObject class should fit your needs.
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
foreach (var property in (IDictionary<String, Object>)employee)
{
Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33
You are asking for dynamic ExpandoObject.
Example:
dynamic obj = new ExpandoObject();
obj.banana = "CIAO";
obj.bidshmqwq = 11245;
obj.BRUFCJMWH = null;
In substance, this Type can let you declare object's properties dynamically.
To convert from a json string to a C# object, you can use the DeserializeObject method and pass in an instance of the c# object that you want to convert this json to. The JsonConvert library is part of the Newtonsoft.Json library.
var converted = JsonConvert.DeserializeObject<myCSharpViewModel>(json);

Error posting record to db asp.net mvc

I am building a scheduling system using fullcalendar for MVC, my get event retrieves from a view for a specific location.
However, my post / save event inserts into the table that the view is made from, containing all locations.
I am getting an error when I try to add the new event to the data connection.
"The field Location must be a string or array type with a maximum length of '1'." string
PropertyName "Location" string
I tried to set the string for the event manually before adding it to the data connection but this isn't working for some reason. Could it be me not declaring the string correctly?
//Actions for Calendar 5
public JsonResult GetEvents5()
{
using (CalgaryNEEntities dc = new CalgaryNEEntities())
{
var events = dc.CalgaryNEEvents.ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
[HttpPost]
public JsonResult SaveEvent5(EventsAllLocation e)
{
var status = false;
using (InsertEntities dc = new InsertEntities())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.EventsAllLocations.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
var locationstring = "Calgary NE Kitchens";
v.CompanyName = e.CompanyName;
v.Start = e.Start;
v.End = e.End;
v.KitchenNumber = e.KitchenNumber;
v.Location = locationstring;
}
}
else
{
var locationstring = "Calgary NE Kitchens";
e.Location = locationstring;
dc.EventsAllLocations.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
Here is the EventsAllLocation definition:
public partial class EventsAllLocation
{
public int EventID { get; set; }
public string Location { get; set; }
public string CompanyName { get; set; }
public System.DateTime Start { get; set; }
public Nullable<System.DateTime> End { get; set; }
public string KitchenNumber { get; set; }
}
Any tips or help would be greatly appreciated, thanks!
The answer is staring you in the face !! LOL
"The field Location must be a string or array type with a maximum
length of '1'." string PropertyName "Location" string

How to pass a variable (besides a set of records) from a controller to a razor view

I have an api controller and a viewmodel as given below that fetch a set of records from an sql db and pass it to a razor view into a kendo grid.
Viewmodel:
public class SoonDueReportsViewModel
{
public SoonDueReportsViewModel()
{
}
public string ARAName { get; set; }
public int? ReportAraId { get; set; }
public string CompanyName { get; set; }
public int? CompanyId { get; set; }
public string ReportDetails { get; set; }
public DateTime? DueReportDate { get; set; }
public int ReportId { get; set; }
}
Controller:
public class AllDueReportsController : BaseApiController
{
private readonly IIdentityStorage identityStorage;
public IQueryable<SoonDueReportsViewModel> Get()
{
AppKatPrincipal appKatPrincipal = identityStorage.GetPrincipal();
var araIds = UnitOfWork.GetAll<UserGroup>()
.Where(group => group.Id == appKatPrincipal.GroupId)
.SelectMany(group => group.ARA).Select(ara => ara.Id);
var duties = UnitOfWork.GetAll<Duty>();
var companies = UnitOfWork.GetAll<Company>();
var aras = UnitOfWork.GetAll<ARA>().Where(x => araIds.Contains(x.Id));
var userGroupId = indireKatPrincipal.GroupId;
var userGroup = UnitOfWork.GetById<UserGroup>(userGroupId);
var foreRun = userGroup.ForRun.GetValueOrDefault();
var nextDate = DateTime.Today.AddMonths(foreRun); // The value of this variable I need to transport also to the view !!
var query = from ara in aras
join company in companies on ara.Id equals company.ARA
join duty in duties on company.Id equals duty.CompanyId
where duty.ReportedDate == null
&& company.Activ == true
select new SoonDueReportsViewModel
{
ARAName = ara.Name,
ReportAraId = ara.Id,
CompanyName = company.Name,
CompanyId = company.ID,
ReportDetails = duty.Details,
DueReportDate = duty.ReportDate,
ReportId = duty.Id,
};
return query;
}
}
Everything works fine, but in addition to the set of records (defined by the query) I also need to transport the value of the variable 'nextDate' to the same view.
If someone could give me a hint how to do this, I'd appreciate it a lot.
Regards, Manu

How to properly clear GridViewExtension data on page revisit or reload?

Background
I have an incomplete project built on MVC 5, EF 6 DB First & DevExpress extensions with following code spec (all original non-English variable names changed & entire code simplified to comply MCVE):
Model (Namespace: ProjectName.Models)
public class DBContext : DbContext
{
public DBContext : base("ConnectionStringName")
{
public DbSet<WinnerTable> Winners { get; set; }
public DbSet<UnitTable> Units { get; set; }
public DbSet<CustomerTable> Customers { get; set; }
}
}
[Table("WinnerTable")]
public class WinnerModel : IWinnerRepository
{
public String WinnerID { get; set; }
public String CustomerID { get; set; }
public String CustomerName { get; set; }
public String TranDate { get; set; }
public List<UnitModel> UnitList { get; set; }
public List<UnitModel> GetUnitList(String sessionID, DateTime tranDate)
{
// query to unit list
using (var DB = new DBContext())
{
var query = (from unit in DB.Units
where unit.SessionID == sessionID && unit.TranDate = tranDate
select new UnitModel()
{
// unit table to unit model definition
}).ToList();
return query;
}
}
}
[Table("UnitTable")]
public class UnitModel
{
public String UnitID { get; set; }
public String UnitName { get; set; }
// other definitions
}
Controller
using ProjectName.Models;
[RoutePrefix("Input")]
public class InputController : Controller
{
[HttpGet]
public ActionResult Winner()
{
WinnerModel model = new WinnerModel()
{
// default values on first visit/reload page
TranDate = DateTime.Now.Date,
UnitList = new List<UnitModel>(); // list declaration
}
return View(model);
}
public PartialViewResult CustomerData(String customerId, String sessionId, DateTime tranDate, WinnerModel model)
{
if (DevExpressHelper.IsCallback && !String.IsNullOrEmpty(customerId))
{
Session["CustomerID"] = customerId;
Session["SessionID"] = sessionId;
Session["TranDate"] = Convert.ToDateTime(tranDate);
using (var DB = new DBContext())
{
var query = DB.Customers.Where(c => c.CustomerID == customerId).FirstOrDefault();
// model property assignments
}
}
return PartialView("_CustomerData", model);
}
public PartialViewResult ShowItemsGrid(WinnerModel model)
{
String customerId = (Session["CustomerId"] ?? String.Empty).ToString();
String sessionId = (Session["SessionId"] ?? String.Empty).ToString();
String lastCustomer = (Session["LastCustomer"] ?? String.Empty).ToString();
DateTime tranDate = Convert.ToDateTime(Session["TranDate"] ?? DateTime.Now.Date);
using (var DB = new DBContext())
{
model.CustomerId = customerId;
model.SessionId = sessionId;
model.TranDate = tranDate;
model.UnitList = model.GetUnitList(sessionId, tranDate);
if (model.UnitList == null || model.UnitList.Count == 0)
{
model.UnitList = new List<UnitModel>();
}
Session["LastCustomer"] = lastCustomer;
return PartialView("_GridView", model);
}
}
}
View (Winner.cshtml)
#using ProjectName.Models
#model WinnerModel
#Html.EnableUnobtrusiveJavascript()
<script type="text/javascript">
var customer = null;
function initializeGrid()
{
ItemsGrid.PerformCallback(); // routine check if customer name exists
}
function comboChanged(s, e) {
customer = s.GetValue();
CustomerDataPanel.PerformCallback(); // callback to fill customer data for partial view & load units into gridview
}
// callback to insert values into session variable
function customerBeginCallback(s, e) {
e.customArgs["customerId"] = customer;
e.customArgs["sessionId"] = SessionId.GetValue();
e.customArgs["tranDate"] = TranDate.GetValue();
}
function customerEndCallback(s, e) {
ItemsGrid.PerformCallback();
}
// count checked data inside gridview
// this may be asked on other context and doesn't matter for this one
function countUnits(buttonName, url)
{
// other code
}
</script>
#using (Html.BeginForm("Winner", "Input", FormMethod.Post))
{
Html.DevExpress().TextBoxFor(m => m.SessionId, TextBoxSettings).GetHtml();
Html.DevExpress().DateEditFor(m => m.TranDate, DateEditSettings).GetHtml();
// this combobox has client-side event SelectedIndexChanged = "comboChanged"
// GetCustomers method just populate customers data into combobox and unrelated to this problem
Html.DevExpress().ComboBoxFor(m => m.CustomerId, ComboBoxSettings).BindList(ProjectName.Providers.GetCustomers()).GetHtml();
Html.RenderPartial("_CustomerData", Model); // DX callback panel
Html.RenderPartial("_GridView", Model);
// button to count all checked values inside gridview
Html.DevExpress().Button(CountButtonSettings).GetHtml();
Html.DevExpress().LabelFor(m => m.TotalPrice, PriceLabelSettings).GetHtml();
// button for submit & reset form here
Html.DevExpress().Button(SubmitButtonSettings).GetHtml();
Html.DevExpress().Button(ResetButtonSettings).GetHtml();
}
Partial View (_CustomerData.cshtml)
#using ProjectName.Models
#model WinnerModel
#{
// MVC DX callback panel for customer details
// Name = CustomerDataPanel
// CallbackRouteValues: Controller = Input, Action = CustomerData
// ClientSideEvents.BeginCallback = customerBeginCallback
// ClientSideEvents.EndCallback = customerEndCallback
Html.DevExpress().CallbackPanel(CallbackPanelSettings).GetHtml();
}
Partial View (_GridView.cshtml)
#using ProjectName.Models
#model WinnerModel
#{
// MVC DX GridView with row selection checkboxes
// The gridview column structure is exactly same as UnitModel has
// Name = ItemsGrid
// CallbackRouteValues: Controller = Input, Action = ShowItemsGrid
// ClientSideEvents.Init = initializeGrid
GridViewExtension grid = Html.DevExpress().GridView(GridViewSettings);
grid.Bind(Model.UnitList).GetHtml(); // grid bound to List<UnitModel>
}
All gridview changes require sufficent privileges (i.e. admin/supervisor).
Problem Statement
I want anyone help finding out where and how proper routine codes to empty gridview data must be attached on controller method(s) to give expected results. As I tried so far, the gridview still maintaining its previous state given from session variable when Winner page revisited or reloaded (immediate first visit after login worked because all session variables are empty, thus no data was populated to gridview).
Additionally, I want to show JS confirm message when user trying to close/reload Winner page while some/all gridview data are being checked.
Expected Results
For every first visit, revisit & reload on Winner page, the gridview content must empty.
After a user provides certain customer ID, the gridview will populated with some unit data from unit table, where changes inside it immediately lost when user accepts reloading/closing page confirm message.
Any kind of answers or suggestions will appreciated.

Deserialize Json in mvc view

In controller I have
public JsonResult Index()
{
List<TutorialModel> models = new List<TutorialModel>();
model.TitleWord = "Go";
model.Colors = new List<bool>();
model.Colors.Add(true);
model.Colors.Add(false);
model.Colors.Add(false);
model.Colors.Add(false);
model.PossibleAnswers = new List<string>();
model.PossibleAnswers.Add("1");
model.PossibleAnswers.Add("2");
model.PossibleAnswers.Add("3");
model.PossibleAnswers.Add("4");
string ser = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(model);
return Json(ser, JsonRequestBehavior.AllowGet);
}
And when In view I try to catch this Json result with
<script>
var values = json.parse(#Model)
</script>
And browser shows me my serialize string. How I can deserialize this json element and store in some variable.
My model for this Controller :
public class TutorialModel
{
public string TitleWord { get; set; }
public List<string> PossibleAnswers { get; set; }
public List<bool> Colors { get; set; }
}
Note that in your Controller, you don't need to return a JsonResult - unless you're calling it as an ajax method or something. In this case, try returning an ActionResult (or ViewResult) as normal. You could do something like this:
public ActionResult Index()
{
List<TutorialModel> models = new List<TutorialModel>();
//...add items to list
return View(models);
}
Then in your cshtml javascript:
<script>
var model = #(Html.Raw(Json.Encode(Model)));
<script>
The problem is that you are returning a JsonResult so all that will be sent to the browser is your JSON, not the view you want.
You need to return a ViewResult:
public ViewResult Index()
{
List<TutorialModel> models = new List<TutorialModel>();
model.TitleWord = "Go";
model.Colors = new List<bool>();
model.Colors.Add(true);
model.Colors.Add(false);
model.Colors.Add(false);
model.Colors.Add(false);
model.PossibleAnswers = new List<string>();
model.PossibleAnswers.Add("1");
model.PossibleAnswers.Add("2");
model.PossibleAnswers.Add("3");
model.PossibleAnswers.Add("4");
string ser = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(model);
return View("Index", ser);
}
Then in your view you can have:
<script>
var values = JSON.parse("#Model")
</script>

Categories

Resources