I have a DropDownListFor that doesn't seem to be setting the expected Model property. Here's the HTML:
#using (Html.BeginForm())
{
#Html.DropDownListFor(x => x.SelectedItem,
new SelectList(Model.ItemList, "Id", "Desc"), null,
new { #class = "selected-list", #size = "3" });
<div>
#Model.SelectedItem
</div>
<input type="submit" value="Do Stuff"
asp-controller="My"
asp-action="DoStuff"
asp-route-itemId="#Model.SelectedItem" />
</div>
}
The div is just there for debugging purposes, and it either shows 0 or blank.
The underlying model has a property:
public int SelectedItem { get; set; }
I've also tried a string:
public string SelectedItem { get; set; } = String.Empty;
(Hence why 0 or blank)
The actual list itself displays fine, it just doesn't update the model on select. How can I get it to update the model?
If you use asp-route-itemId, your action need contains parameter named itemId to receive the value. But for your scenario, it seems to be useless to receive such value, because it will always receive the value you set instead of the dropdown changed value.
Here is a simple demo you could follow and check if any difference with yours:
Model
public class TestVM
{
public string SelectedItem { get; set; } = String.Empty;
public List<Item> ItemList { get; set; }
}
public class Item
{
public int Id { get; set; }
public string Desc { get; set; }
}
View(Index.cshtml)
#model TestVM
#using (Html.BeginForm())
{
#Html.DropDownListFor(x => x.SelectedItem,
new SelectList(Model.ItemList, "Id", "Desc"), null,
new { #class = "selected-list", #size = "3" });
<div>
#Model.SelectedItem
</div>
<input type="submit" value="Do Stuff"
asp-controller="Home"
asp-action="DoStuff" />
}
Controller
[HttpGet]
public IActionResult Index()
{
//Note: hard-coded the model just for easy testing.....
var model = new TestVM()
{
SelectedItem = "1",
ItemList = new List<Item>()
{
new Item(){Id=1,Desc="aa"},
new Item(){Id=2,Desc="bb"},
new Item(){Id=3,Desc="cc"}
}
};
return View(model);
}
[HttpPost]
public IActionResult DoStuff(TestVM model)
{
return View("index", model);
}
Result
I have this model
public class foo
{
public foo()
{
this.barList = new List<bar>();
}
public string name { get; set; }
public List<bar> barList { get; set; }
}
public class bar
{
public string sample1 { get; set; }
public string sample2 { get; set; }
public string sample3 { get; set; }
}
I am trying to display these values in view but I am not able to display the value that is supposedly be displayed in Html.DropDownListFor
Here is how I render it on my view:
#foreach (var item in Model.barList)
{
<div>
#item.sample1
</div>
<div>
#{
var status = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "text1", Value = "value1"},
new SelectListItem {Text = "text2", Value = "value2"},
new SelectListItem {Text = "text3", Value = "value3"}
}, "Value", "Text");
}
#Html.DropDownListFor(m => item.sample2, status, "-- Select -- ", new { #class = "w100 form-control" })
</div>
<div>
#item.sample3
</div>
}
What I am trying to do is set the selected value for the DropDownList to the value in the variable sample2 on which value it matches on the select list. But somehow there is no value that is being selected when I try this code.
I have a class:
public class StatististikaByCustomer
{
public string data { get; set; } // Array or String?
public string xkey {get;set;}
public Array ykey {get;set;}
public Array labels {get;set;}
}
How can I get JSON like this?
{
"data":[
{
"timeinterval":"2015-10-22T00:00:00",
"Firm":4,
"Firm1":4,
"Firm2":22,
"Firm3":30,
"Firm4":19
},
{
"timeinterval":"2015-10-23T00:00:00",
"Firm":2,
"Firm1":5,
"Firm2":29,
"Firm3":34,
"Firm4":219
}
],
"xkey":"timeinterval",
"ykey":["Firm","Firm1","Firm2","Firm3","Firm4"],
"labels":[" Firm","Firm1","Firm2","Firm3","Firm4"]
}
Firm cannot be hard coded. It all must be dynamic.
My Controller Action:
public JsonResult StatistikaJson()
{
ArrayList arrayList = new ArrayList();
StatistikaByCustomer statisikaObject = new StatistikaByCustomer();
List<Data> listData = new List<Data>();
string jsonTemp = null;
DbDataReader reader = null;
using (var cmd = db.Database.Connection.CreateCommand())
{
if (db.Database.Connection.State == ConnectionState.Closed)
{
db.Database.Connection.Open();
}
cmd.CommandText = "EXEC GetClientConnectsByCustomer #start='" + DateTime.Now.AddMonths(-1).Date.ToString("yyyy-MM-dd") + "',#end='" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "',#interval = 24";
reader = cmd.ExecuteReader();
var tempYkey = Enumerable.Range(1, reader.FieldCount - 1).Select(reader.GetName).ToArray();
statisikaObject.ykey = tempYkey.Select(x => x.Replace(" ", "")).ToArray();
if (reader.HasRows)
{
while (reader.Read())
{
string name = reader.GetName(0);
object value = reader.GetDateTime(0);
listData.Add(new Data() { Name = name, Value = value });
for (int i = 1; i < reader.FieldCount - 1; i++)
{
name = reader.GetName(i).Replace(" ", "");
value = reader.GetInt32(i);
listData.Add(new Data() { Name = name, Value = value });
}
//arrayList.Add(JsonConvert.SerializeObject(listData.ToDictionary(x => x.Name, y => y.Value)));
jsonTemp += JsonConvert.SerializeObject(listData.ToDictionary(x => x.Name, y => y.Value));
jsonTemp += ",";
listData.Clear();
//Debug.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", reader.GetName(0), reader.GetDateTime(0), reader.GetInt32(1), reader.GetInt32(2), reader.GetInt32(3), reader.GetInt32(4));
}
}
else
{
Debug.WriteLine("No rows found.");
}
statisikaObject.xkey = reader.GetName(0);
statisikaObject.labels = Enumerable.Range(1, reader.FieldCount - 1).Select(reader.GetName).ToArray();
reader.Close();
//the number of affected records, if the query returns it var result = cmd.ExecuteNonQuery();
//or a single scalar value //var result = cmd.ExecuteScalar();
//or even a data reader var result = cmd.ExecuteReader();
db.Database.Connection.Close();
}
statisikaObject.data = oSerializer.Serialize(arrayList);
//string json = JsonConvert.SerializeObject(statisikaObject);
//string json = JsonConvert.SerializeObject(l);
return Json(statisikaObject, JsonRequestBehavior.AllowGet);
}
I get JSON, but it's escaped and morris.js doesn't like it.
In my view, I would like to use it like this:
<script type="text/javascript">
$.getJSON('#Url.Action("StatistikaJson")', function (result)
{
new Morris.Line({
element: 'line-example',
data: result.data,
xkey: "timeinterval",
ykeys: result.ykey,
labels: result.labels
});
});
</script>
I can use Json.NET if necessary. If posible, I would like to get ride off the JSON string appending. I would like to have an array and call serialize to get data: json objects in array format that morris.js needs: http://jsbin.com/uqawig/441/embed?js,output
{"data":"{"timeinterval":"2015-10-22T00:00:00","Firm":4,...},{"timeinterval":"2015-10-22T00:00:00","Firm":5,...},...}
ViewModel:
public class StatistikaByCustomer
{
public ArrayList data { get; set; }
public string xkey { get; set; }
public List<string> ykey { get; set; }
public List<string> labels { get; set; }
}
Controller:
public JsonResult StatistikaJson()
{
StatistikaByCustomer statisikaObject = new StatistikaByCustomer();
ArrayList arrayList = new ArrayList();
List<Data> listData = new List<Data>();
DbDataReader reader = null;
using (var cmd = db.Database.Connection.CreateCommand())
{
if (db.Database.Connection.State == ConnectionState.Closed)
{
db.Database.Connection.Open();
}
cmd.CommandText = "EXEC GetClientConnectsByCustomer #start='" + DateTime.Now.AddMonths(-1).Date.ToString("yyyy-MM-dd") + "',#end='" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "',#interval = 24";
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
string name = reader.GetName(0);
object value = reader.GetDateTime(0).ToString("yyyy-MM-dd");
listData.Add(new Data() { Name = name, Value = value });
for (int i = 1; i <= reader.FieldCount - 1; i++)
{
name = reader.GetName(i).Replace(" ", "");
value = reader.GetInt32(i);
listData.Add(new Data() { Name = name, Value = value });
}
arrayList.Add(JsonConvert.SerializeObject(listData.ToDictionary(x => x.Name, y => y.Value)));
listData.Clear();
//Debug.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", reader.GetName(0), reader.GetDateTime(0), reader.GetInt32(1), reader.GetInt32(2), reader.GetInt32(3), reader.GetInt32(4));
}
}
statisikaObject.data = arrayList;
statisikaObject.xkey = reader.GetName(0);
statisikaObject.labels = Enumerable.Range(1, reader.FieldCount - 1).Select(reader.GetName).ToList();
var tempYkey = Enumerable.Range(1, reader.FieldCount - 1).Select(reader.GetName).ToArray();
statisikaObject.ykey = tempYkey.Select(x => x.Replace(" ", "")).ToList();
reader.Close();
db.Database.Connection.Close();
}
return Json(statisikaObject, JsonRequestBehavior.AllowGet);
}
View:
<script type="text/javascript">
$.getJSON('#Url.Action("StatistikaJson")', function (result)
{
new Morris.Line({
element: 'line-example',
data: $.parseJSON("[" + result.data + "]"),
xkey: result.xkey,
ykeys: result.ykey,
labels: result.labels
});
});
</script>
public class Datum
{
public string timeinterval { get; set; }
public int Firm { get; set; }
public int Firm1 { get; set; }
public int Firm2 { get; set; }
public int Firm3 { get; set; }
public int Firm4 { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
public string xkey { get; set; }
public List<string> ykey { get; set; }
public List<string> labels { get; set; }
}
By putting this code get Serialize json string
var collection = new List<RootObject>();
dynamic collectionWrapper = new
{
people = new RootObject()
{
xkey = "timeinterval",
data = new List<Datum>
{
new Datum()
{
timeinterval = "2015-10-22T00: 00: 00",
Firm = 4,
Firm1= 4,
Firm2= 22,
Firm3= 30,
Firm4= 19
},
new Datum()
{
timeinterval = "2015-10-23T00: 00: 00",
Firm = 2,
Firm1= 5,
Firm2= 29,
Firm3= 34,
Firm4= 219
}
},
ykey = new List<string> { "Firm", "Firm1", "Firm2", "Firm3", "Firm4" },
labels = new List<string> { "Firm", "Firm1", "Firm2", "Firm3", "Firm4" }
}
};
var output = JsonConvert.SerializeObject(collectionWrapper);
Edit:
var collection = new StatististikaByCustomer
{
xkey = "timeinterval",
ykey = new List<string>{"Firm","Firm1","Firm2","Firm3","Firm4"},
labels = new List<string> { "Firm", "Firm1", "Firm2", "Firm3", "Firm4" },
data = new Dictionary<string, string>
{
{ "timeinterval", "2015-10-22T00: 00: 00" },
{ "Firm", "4" },
{ "Firm1", "4" },
{ "Firm2", "22" },
{ "Firm3", "30" },
{ "Firm4", "19" }
}
};
string json = JsonConvert.SerializeObject(collection);
Class:
public class StatististikaByCustomer
{
public string xkey { get; set; }
public Dictionary<string, string> data { get; set; }
public List<string> ykey { get; set; }
public List<string> labels { get; set; }
}
Update:
var collection = new StatististikaByCustomer
{
xkey = "timeinterval",
ykey = new List<string> { "Firm", "Firm1", "Firm2", "Firm3", "Firm4" },
labels = new List<string> { "Firm", "Firm1", "Firm2", "Firm3", "Firm4" },
data = new List<Dictionary<string,string>>
{
new Dictionary<string, string>
{
{ "timeinterval", "2015-10-22T00: 00: 00" },
{ "Firm", "4" },
{ "Firm1", "4" },
{ "Firm2", "22" },
{ "Firm3", "30" },
{ "Firm4", "19" }
},
new Dictionary<string, string>
{
{ "timeinterval", "2015-10-23T00: 00: 00" },
{ "Firm", "2" },
{ "Firm1", "5" },
{ "Firm2", "29" },
{ "Firm3", "34" },
{ "Firm4", "219" }
}
}
};
string json = JsonConvert.SerializeObject(collection);
Class:
public class StatististikaByCustomer
{
public string xkey { get; set; }
public List<Dictionary<string, string>> data { get; set; }
public List<string> ykey { get; set; }
public List<string> labels { get; set; }
}
I got a view with some textbox and a submit button
when i push submit i want the data of the textboxes in a json file(no database)
Now it works only for save 1data command when i psuh a second time on submit with other data
then hen rewrite my json file how can i save all of it ?
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
// jsonkalender.Add(new kalender() { Password = "" });
//kalender kl = new kalender();
//kl.Password = obj.Password;
//kl.MyEnum = TestEnum.taak;
//obj.Password = kl.Password;
//Load(null);
return View();
}
private const string JsonFileName1 = #"C:\\Users\Alexander\Desktop\times1.json";
private List<kalender> _times;
[HttpPost]
public ActionResult Index(kalender obj)
{
// Load(obj);
// _times.Add(new kalender() { Datum = DateTime.Now.ToString() });
kalender kl = new kalender();
Json(new { datum = obj.Datum,wachtwoord = obj.Password });
// _times.Add(obj);
try
{
}
catch (Exception) { }
obj.SelectedEnumId++;
// kl.Password = obj.Password;
var json = JsonConvert.SerializeObject(obj, Formatting.Indented);
using (var writer = new StreamWriter(JsonFileName1))
{
writer.Write(json);
}
return View();
}
private void Load(kalender obj)
{
if (System.IO.File.Exists(JsonFileName1))
{
using (var reader = new StreamReader(JsonFileName1))
{
var json = reader.ReadToEnd();
obj = JsonConvert.DeserializeObject<kalender>(json);
}
}
if (obj == null)
obj = new kalender();
}
}
}
Model
public class kalender
{
//public string Datum { get; set; }
// [Required]
// [DataType(DataType.Date)]
// public Nullable<System.DateTime> Datum { get; set; }
public string Datum { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string Type { get; set; }
[Required]
[Key]
public int SelectedEnumId { get; set; }
[Required]
public TestEnum MyEnum { get; set; }
}
}
View
#model PE1.Models.kalender
#{
ViewBag.Title = "Index";
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
}
#{
AjaxOptions options = new AjaxOptions();
options.HttpMethod = "POST";
options.Confirm = "Zeker?";
options.OnBegin = "OnBegin";
options.OnComplete = "OnComplete";
options.OnFailure = "OnFailure";
options.OnSuccess = "OnSuccess";
options.LoadingElementId = "divProgress";
options.LoadingElementDuration = 1000;
options.UpdateTargetId = "divResponse";
options.InsertionMode = InsertionMode.InsertAfter;
}
<script type="text/javascript">
$(function () { // will trigger when the document is ready
$('.datepicker').datepicker(); //Initialise any date pickers
});
</script>
<div>
<h1>Online Kalender</h1>
<div id="kader">
<p>THuis</p>
#using (Html.BeginForm("Index", "Home", options))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Kaldender</legend>
#*#Html.DropDownListFor(model => model.Password, listItems)*#<br />
#Html.LabelFor(model => model.Password)<br />
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)<br />
#Html.EnumDropDownListFor(model => model.MyEnum)
<div class="form-group input-group-sm">
#Html.LabelFor(model => model.Datum)
#Html.TextBoxFor(model => model.Datum, new { #class = "form-control datepicker", placeholder = "Enter Drop-off date here..." })
#Html.ValidationMessageFor(model => model.Datum)
</div>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset"/>
</fieldset>
#Ajax.ActionLink("Klik hier om een Ajax ActionLink uit te voeren", "ProcessLink", options)
}
enum
public enum TestEnum : int
{
taak,
vergadering
}
my output is wrong how can i change it ?
{
"Datum": "10/28/2014",
"Password": "hrth",
"Type": null,
"SelectedEnumId": 0,
"MyEnum": 0,
"rand1": 0
}{
"Datum": "10/28/2014",
"Password": "hrth",
"Type": null,
"SelectedEnumId": 0,
"MyEnum": 0,
"rand1": 0
}
this is my json file but i need this
[
{
"Datum": "10/28/2014",
"Password": "hrth",
"Type": null,
"SelectedEnumId": 0,
"MyEnum": 0,
"rand1": 0
},{
"Datum": "10/28/2014",
"Password": "hrth",
"Type": null,
"SelectedEnumId": 0,
"MyEnum": 0,
"rand1": 0
}
]
Use the Overload for the SteamWriter object that appends to a file instead of overwriting a file.
http://msdn.microsoft.com/en-us/library/36b035cb(v=vs.110).aspx
using (var writer = new StreamWriter(JsonFileName1, true))
{
writer.Write(json);
}
Notice the addition of the bool true in the StreamWriter constructor
This is Razor Syntax for ListBox i am using in my page. How can i set its height and width ?
Here noCategories is View data coming from Controller.
$
#Html.ListBox("noCategories");
Controller:
public ActionResult Configure(int? nopCategoryid)
{
model = new DataImporttModel();
DisplaynopCommerceCategories(model, nopCategoryid);
return View("Nop.Plugin.Data.Import.Views.DataImport.Configure", model);
}
private void DisplaynopCommerceCategories(DataImporttModel model, int? nopCategoryid)
{
var _categoryservice = new NopEngine().Resolve<ICategoryService>();
MultiSelectList sl;
model.nopCommerceCategories = new List<CS_ListItems>();
foreach (var item in _categoryservice.GetAllCategories().ToList())
{
model.nopCommerceCategories.Add(new CS_ListItems() { Name = item.Name, ID = item.Id });
}
if (nopCategoryid != null)
{
sl = new MultiSelectList(model.nopCommerceCategories, "ID", "Name", new[] { nopCategoryid });
}
else
{
sl = new MultiSelectList(model.nopCommerceCategories, "ID", "Name");
}
ViewData["nopCommerceCategories"] = sl;
}
public class DataImporttModel
{
public List<C_Category> Mappings { get; set; }
public List<CS_ListItems> ClockCategories { get; set; }
public List<CS_ListItems> nopCommerceCategories { get; set; }
}
You can apply a class to it and then style it through CSS:
#Html.ListBox("noCategories", ViewData["nopCommerceCategories"] as MultiSelectList, new {#class = "mylistbox"});
CSS
.myclass{
width: 100px;
}
Alternatively, you can style it inline:
#Html.ListBox("noCategories", ViewData["nopCommerceCategories"] as MultiSelectList, new {#style = "width: 100px;"});