I have listbox
#Html.ListBox("lais", new SelectList(Model.lista, "Value", "Text"), new {#class = "mylistbox"});
Here am getting list data but not binding to listbox (list items value )
This is my action method
public ActionResult PrintRFIDTag()
{
Print p =new Print();
p.lista = GetList();
return View(p);
}
public SelectList GetList()
{
System.Management.ManagementScope objMS =
new System.Management.ManagementScope(ManagementPath.DefaultPath);
objMS.Connect();
List<SelectListItem> items = new List<SelectListItem>();
SelectQuery objQuery = new SelectQuery("SELECT * FROM Win32_Printer");
ManagementObjectSearcher objMOS = new ManagementObjectSearcher(objMS, objQuery);
System.Management.ManagementObjectCollection objMOC = objMOS.Get();
foreach (ManagementObject Printers in objMOC)
{
if (Convert.ToBoolean(Printers["Network"])) // ALL NETWORK PRINTERS.
{
var emptyItem = new SelectListItem()
{
Value = Printers["Name"].ToString(),
Text = "00"
};
items.Add(emptyItem);
}
}
SelectList objselectlist = new SelectList(items,"Value");
return objselectlist;
}
}
Here is my model class
public class Print
{
public SelectList lista { get; set; }
public string Name { get; set; }
}
Returning from view but not binding to listbox
Your help will be appropriated
try this:
#Html.ListBoxFor(m=>m.lista ,Model.lista) and change line SelectList objselectlist = new SelectList(items,"Value"); to this: SelectList objselectlist = new SelectList(items,"Value","Text");
Related
I have the following class:
public class MenuItem
{
public string Title { get; set; }
public List<MenuItem> Items { get; set; }
public MenuItem()
{
Items = new List<MenuItem>();
}
}
How it is possible to properly serialize this?
Adrian Tarniceru
and I created a tree of MenuItem objects and wanted to serialize it with YamlDotNet but the result was unexpected.
MenuItem _root = new MenuItem() { Title = "Menu" };
MenuItem childItem1 = new MenuItem() { Title = "Child item #1" };
childItem1.Items.Add(new MenuItem() { Title = "Child item #1.1" });
childItem1.Items.Add(new MenuItem() { Title = "Child item #1.2" });
_root.Items.Add(childItem1);
_root.Items.Add(new MenuItem() { Title = "Child item #2" });
var serializer = new Serializer();
string fileContent = serializer.Serialize(_root);
using (StreamWriter writer = new StreamWriter("Menu.yaml"))
{
writer.Write(fileContent);
}
result was:
...
bu I expected a tree of MenuItems in Yaml.
I am trying to iterate through an SQL query and set the objects parameters to particular values. The only value that seems to be functioning correctly is the workpack.JobCardIDs, as I can implement a foreach loop to display the results. If I try to set a Label's Text property to a workpack.WorkPackTitle for example, it will display a blank even though the database value is something for every line.
I am fairly new to the OOP so not entirely sure if there is something I am missing that's fundamental.
public class WorkPack
{
public int ID { get; set; }
public string WorkPackNumber { get; set; }
public string WorkPackTitle { get; set; }
public string WorkPackDescription { get; set; }
public Boolean IFC { get; set; }
public string SPA { get; set; }
public string Writer { get; set; }
public string Organization { get; set; }
public List<int> JobCardIDs { get; set; }
public int JobCard { get; set; }
}
public static WorkPack PopulateWorkPackObject(WorkPack workpack, int workPackID)
{
string ConnectionString = ConfigurationManager.ConnectionStrings["vmdatamanagerConnectionString"].ConnectionString;
string sqlCall = "I HAVE REMOVED CALL BUT VERIFIED IT FUNCTIONS (SELECT columns FROM workpackdatabase where workpackname = x";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlCall, con))
{
cmd.Connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (reader.IsDBNull(reader.GetOrdinal("PARAM1")) == false)
workpack.WorkPackNumber = (reader.GetString(reader.GetOrdinal("PARAM1")));
if (reader.IsDBNull(reader.GetOrdinal("PARAM2")) == false)
workpack.WorkPackTitle = reader.GetString(reader.GetOrdinal("PARAM2"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM3")) == false)
workpack.WorkPackDescription = reader.GetString(reader.GetOrdinal("PARAM3"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM4")) == false)
workpack.IFC = reader.GetBoolean(reader.GetOrdinal("PARAM4"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM5")) == false)
workpack.SPA = reader.GetString(reader.GetOrdinal("PARAM5"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM6")) == false)
workpack.Writer = reader.GetString(reader.GetOrdinal("PARAM6"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM7")) == false)
workpack.Organization = reader.GetString(reader.GetOrdinal("PARAM7"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM8")) == false)
jobCardIDs.Add(reader.GetInt32(reader.GetOrdinal("PARAM8")));
}
workpack.JobCardIDs = jobCardIDs;
return workpack;
}
}
}
}
Looks like you never create a local instance of your jobCardIDs List. You'll want to do this just inside your ExecuteReader block. See below. GL
public static WorkPack PopulateWorkPackObject(WorkPack workpack, int workPackID)
{
string ConnectionString = ConfigurationManager.ConnectionStrings["vmdatamanagerConnectionString"].ConnectionString;
string sqlCall = "I HAVE REMOVED CALL BUT VERIFIED IT FUNCTIONS (SELECT columns FROM workpackdatabase where workpackname = x";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlCall, con))
{
cmd.Connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
List<int> jobCardIDs = new List<int>(); //<--***THIS IS THE LINE YOU NEED TO ADD***
while (reader.Read())
{
if (reader.IsDBNull(reader.GetOrdinal("PARAM1")) == false)
workpack.WorkPackNumber = (reader.GetString(reader.GetOrdinal("PARAM1")));
if (reader.IsDBNull(reader.GetOrdinal("PARAM2")) == false)
workpack.WorkPackTitle = reader.GetString(reader.GetOrdinal("PARAM2"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM3")) == false)
workpack.WorkPackDescription = reader.GetString(reader.GetOrdinal("PARAM3"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM4")) == false)
workpack.IFC = reader.GetBoolean(reader.GetOrdinal("PARAM4"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM5")) == false)
workpack.SPA = reader.GetString(reader.GetOrdinal("PARAM5"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM6")) == false)
workpack.Writer = reader.GetString(reader.GetOrdinal("PARAM6"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM7")) == false)
workpack.Organization = reader.GetString(reader.GetOrdinal("PARAM7"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM8")) == false)
jobCardIDs.Add(reader.GetInt32(reader.GetOrdinal("PARAM8")));
}
workpack.JobCardIDs = jobCardIDs;
return workpack;
}
}
}
}
The previous answers given by the community did not fix the issue, although I did put that extra snippet it.
The issue was when the objects were being created and passed between post backs. The object would be relevant on selection of the job card tab but once the page loaded there was no code to rebuild that instance.
Adding
Object foo = new Object();
in the page_Load() and rebuilding fixed the issue. If anyone has any suggestions on how to keep an instance alive I am all for hearing it. I think ViewState() and also Session[] were applicable methods for doing so.
I am retrieving records from store procedure, but it does not bind data into view.
Here is ModelContext class:
namespace MyTesting.Models
{
public class TvSerialDB
{
public static string constr = ConfigurationManager.ConnectionStrings["TvSerialContext"].ConnectionString;
SqlConnection con;
SqlCommand cmd;
public IEnumerable<TVSerialByGroup> tvserialgroupby(string serialname)
{
List<TVSerialByGroup> tvserials = new List<TVSerialByGroup>();
using (con = new SqlConnection(constr))
{
cmd = new SqlCommand("pSerialListGroupBySerialName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#SerialName", SqlDbType.VarChar, 100).Value = serialname;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
TVSerialByGroup tvs = new TVSerialByGroup();
tvs.Series_Name = sdr["Series_Name"].ToString();
tvs.Image_Url_Big = sdr["Image_Url_Big"].ToString();
tvs.Season_No = sdr["Season_No"].ToString();
tvs.TotalEpisode = sdr["TotalEpisode"].ToString();
}
}
return tvserials;
}
}
}
Here is ModelClass:
namespace MyTesting.Models
{
public class TVSerialByGroup
{
public string Series_Name { get; set; }
public string Season_No { get; set; }
public string Image_Url_Big { get; set; }
public string TotalEpisode { get; set; }
}
}
Here is controller class:
public ActionResult ListAllSeason(string serial)
{
try
{
TvSerialDB tvcon = new TvSerialDB();
List<TVSerialByGroup> tv = tvcon.tvserialgroupby(serial).ToList();
return View(tv);
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
When i run this application it does not display any record nor it gives error.
When i debug this code through breakpoint it returns rows into store procedure but in views it does not bind data.
You not adding your model instances to the collection.
while (sdr.Read())
{
TVSerialByGroup tvs = new TVSerialByGroup();
tvs.Series_Name = sdr["Series_Name"].ToString();
tvs.Image_Url_Big = sdr["Image_Url_Big"].ToString();
tvs.Season_No = sdr["Season_No"].ToString();
tvs.TotalEpisode = sdr["TotalEpisode"].ToString();
tvserials.Add(tvs); // add this
}
Side note: Since your initializing List<TVSerialByGroup>, you can make your method public List<TVSerialByGroup> tvserialgroupby(string serialname) and then you do not need .ToList(); in the ActionResult method.
I have the following code inside my model class :-
public class PageOptions
{
public PageOptions()
{
int size = Int32.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"]);
NameSelectionOptions = new SelectList(
new List<SelectListItem> {
new SelectListItem { Text=size.ToString(), Value = size.ToString()},
new SelectListItem { Text="50", Value = "50"},
new SelectListItem { Text="100", Value = "100"},
new SelectListItem { Text="200", Value = "200"},
new SelectListItem { Text="500", Value = "500"}
}, "Value", "Text");
}
public SelectList NameSelectionOptions { get; set; }
}
}
but how i can display the SelectList inside a Html.DropDownList ? and setting the default valueto be size?
Thanks
You simply pass the desired selection as a 4th parameter to the SelectList constructor:
NameSelectionOptions = new SelectList(
new List<SelectListItem> {
new SelectListItem { Text=size.ToString(), Value = size.ToString()},
new SelectListItem { Text="50", Value = "50"},
new SelectListItem { Text="100", Value = "100"},
new SelectListItem { Text="200", Value = "200"},
new SelectListItem { Text="500", Value = "500"}
}, "Value", "Text", size); // <<< Add size here
This is far more flexible than selecting a specific item in the list.
There are several options for binding a list to the view. You can use a property in the ViewModel, however standard practice (as per Microsoft's scaffolding templates) is to pass dropdown lists to a view in a ViewBag entry of the same name as the Model property. This has the added bonus of automatically binding the simpler #Html.DropDownList("Size") version to both a Model property called Size and the list in ViewBag.Size.
e.g.
In Controller:
ViewBag.Size = new SelectList(
new List<SelectListItem> {
new SelectListItem { Text=size.ToString(), Value = size.ToString()},
new SelectListItem { Text="50", Value = "50"},
new SelectListItem { Text="100", Value = "100"},
new SelectListItem { Text="200", Value = "200"},
new SelectListItem { Text="500", Value = "500"}
}, "Value", "Text", size); // <<< Add size here
viewModel.Size = size;
return View(viewModel);
Where viewModel contains any properties you want edited (including Size).
In View:
#Html.DropDownList("Size")
or if you prefer the strongly typed version.
#Html.DropDownListFor(m=>m.Size, (SelectList)ViewBag.Size)
In any case the consistent naming will help avoid problems.
Default values can go in the ViewBag, but the selection should be bound to your ViewModel so you can use the same ViewModel to receive the posted back values.
#Html.DropDownListFor(m=>m.Size, (SelectList)ViewBag.Size, ViewBag.DefaultSize)
Update:
If you do not wish to bind the current value to anything (as per comment), you simply need to have the ViewBag.Size set to you SelectList by the controller and have this is the View. You do not need a value in the Model.
#Html.DropDownList("Size")
The default selection will be the selection (4th parameter, size) in new SelectList() above.
Simply add Selected property in it:
new SelectListItem { Text=size.ToString(),
Value = size.ToString(),
Selected = true}
Model:
public class PageOptions
{
public PageOptions()
{
int size = Int32.Parse("20");
NameSelectionOptions = new SelectList(
new List<SelectListItem> {
new SelectListItem { Text=size.ToString(), Value = size.ToString()},
new SelectListItem { Text="50", Value = "50"},
new SelectListItem { Text="100", Value = "100"},
new SelectListItem { Text="200", Value = "200"},
new SelectListItem { Text="500", Value = "500"}
}, "Value", "Text");
}
public SelectList NameSelectionOptions { get; set; }
public string SelectedValue { get; set; }
}
Action:
public ActionResult Index()
{
PageOptions model = new PageOptions();
return View(model);
}
Strongly Typed View:
#model TestAjaxUpload.Models.PageOptions
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#Html.DropDownListFor(x=>x.SelectedValue,Model.NameSelectionOptions)
if you want to do without changing your current model for view then, create instance inside view and pass like this:
#model SomeModelClass
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#{
TestAjaxUpload.Models.PageOptions objModel = new TestAjaxUpload.Models.PageOptions();
}
#Html.DropDownListFor(x=>x.SelectedValue,objModel.NameSelectionOptions)
but you should add PageOptions SelectList as property in your Model and use it, i don't recommend to do directly in View.
Update (Using ViewBag):
with ViewBag you can do this way:
public ActionResult Index()
{
PageOptions model = new PageOptions();
ViewBag.List = model.NameSelectionOptions;
ViewBag.Selected = "20";
return View(model);
}
in View:
#Html.DropDownListFor(x=>x.SelectedValue,ViewBag.List as SelectList,ViewBag.Selected as string)
I've been playing a little with the MongoDB Bson serializer, using the following piece of code:
class Program
{
public class myValue
{
public int Id = 0;
public string Label = "";
}
public class myValueMap : Dictionary<string, myValue>
{
}
public class myProdData
{
public myValueMap Mapping { get; set; }
}
public class mySystemPosition
{
public string Text { get; set; }
public myProdData ProdData { get; set; }
}
static void Main(string[] args)
{
BsonClassMap.RegisterClassMap<mySystemPosition>();
BsonClassMap.RegisterClassMap<myProdData>();
BsonClassMap.RegisterClassMap<myValueMap>();
BsonClassMap.RegisterClassMap<myValue>();
var o = new mySystemPosition()
{
ProdData = new myProdData()
{
Mapping = new myValueMap()
{
{"123", new myValue() {Id = 1, Label = "Item1"}},
{"345", new myValue() {Id = 2, Label = "Item2"}},
}
}
};
var bson = o.ToBson();
var text = Encoding.ASCII.GetString(bson);
}
}
however I don't seem to be able to get the myProdData.Mapping serialized....
Do I need to configure the MongoDB Bson serializer in a special way, to make this work?
You no need to use BsonClassMap.RegisterClassMap if you no need custom serializtion(documentation).
All your classes will be desirialzied according to default rules.
Also i am changed your example a little bit to get it work(i've replaces myValueMap class with Dictionary):
public class myProdData
{
public Dictionary<string, myValue> Mapping { get; set; }
}
static void Main(string[] args)
{
var o = new mySystemPosition()
{
ProdData = new myProdData()
{
Mapping = new Dictionary<string, myValue>()
{
{"123", new myValue() {Id = 1, Label = "Item1"}},
{"345", new myValue() {Id = 2, Label = "Item2"}},
}
}
};
var json = o.ToJson();
Console.WriteLine(json);
Console.ReadKey();
}
Here is console output(just well formatted):
{
"Text":null,
"ProdData":{
"Mapping":{
"123":{
"_id":1,
"Label":"Item1"
},
"345":{
"_id":2,
"Label":"Item2"
}
}
}
}
You can test your serializtion using ToJson() extention method, in order to view that all correct and after that use ToBson() if need.
The problem is that myValueMap derives from Dictionary. That results in a class that the AutoMap method can't handle.
I recommend you just use the Dictionary directly, as Andrew did in his reply.
Ufortunately the myValueMap is an object that I can't easily change, however it turns out, that's pretty easy to create your own (de)serializer....
public class myValueMapSerializer : IBsonSerializer
{
public object Deserialize(Bson.IO.BsonReader bsonReader, System.Type nominalType, System.Type actualType, IBsonSerializationOptions options)
{
if (nominalType != typeof(myValueMap)) throw new ArgumentException("Cannot serialize anything but myValueMap");
var res = new myValueMap();
var ser = new DictionarySerializer<string, myValue>();
var dic = (Dictionary<string, myValue>)ser.Deserialize(bsonReader, typeof(Dictionary<string, myValue>), options);
foreach (var item in dic)
{
res.Add(item.Key, item.Value);
}
return res;
}
public object Deserialize(Bson.IO.BsonReader bsonReader, System.Type nominalType, IBsonSerializationOptions options)
{
throw new Exception("Not implemented");
}
public bool GetDocumentId(object document, out object id, out IIdGenerator idGenerator)
{
id = null;
idGenerator = null;
return false;
}
public void Serialize(Bson.IO.BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
{
if (nominalType != typeof(myValueMap)) throw new ArgumentException("Cannot serialize anything but myValueMap");
var ser = new DictionarySerializer<string, myValue>();
ser.Serialize(bsonWriter, typeof(DictionarySerializer<string, myValue>), value, options);
}
public void SetDocumentId(object document, object id)
{
return;
}
}