MVC json save file - json

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

Related

Edit User Data with savechanges modelstate.Isvaild problem

I want to update user details like Firstname, Lastname and date-of-birth. although the ModelState is valid and SaveChanges doesn't work. I got some errors for ModelState which are about password and email fields.
the error about SaveChanges is about confirmpassword partial class I think that's what errors say!
Error = The function evaluation requires all threads to run.
{"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."}
here are my files
database UI
database table user with datatype
Registration and password usage
public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")] User user)
{
bool Status = false;
string message = "";
//
// Model Validation
if (ModelState.IsValid)
{
#region //Email is already Exist
var isExist = IsEmailExist(user.EmailID);
if (isExist)
{
ModelState.AddModelError("EmailExist", "ایمیل شما قبلا ثبت شده است");
return View(user);
}
#endregion
#region Generate Activation Code
user.ActivationCode = Guid.NewGuid();
#endregion
#region Password Hashing
user.Password = Crypto.Hash(user.Password);
user.Confirmpassword = Crypto.Hash(user.Confirmpassword); //
#endregion
user.IsEmailVerified = false;
#region Save to Database
using (sitedatabaseEntities1 dc = new sitedatabaseEntities1())
{
dc.Users.Add(user);
dc.SaveChanges();
//Send Email to User
SendVerificationLinkEmail(user.EmailID, user.ActivationCode.ToString());
message = "تبریک ثبت نام شما با موفقیت انجام شد. " +
" و کد فعال سازی برای شما ارسال گردید به ایمیل:" + user.EmailID;
Status = true;
}
#endregion
}
else
{
message = "درخواست نادرست";
}
ViewBag.Message = message;
ViewBag.Status = Status;
return View(user);
}
profile view() usercontroller.cs
public ActionResult profile()
{
using (sitedatabaseEntities1 db = new sitedatabaseEntities1())
{
int userid = int.Parse(Request.Cookies["userid"].Value);
return View(db.Users.Where(x => x.UserID == userid).FirstOrDefault());
}
}
[HttpPost]
public ActionResult profile([Bind(Include = "UserID,FirstName,LastName,DateOfBirth")] User user)
{
var message = "";
if (ModelState.IsValid)
{
if (user != null)
{
var account = db.Users.Where(a => a.UserID == user.UserID).FirstOrDefault();
account.FirstName = user.FirstName;
account.LastName = user.LastName;
account.DateOfBirth = user.DateOfBirth;
db.SaveChanges();
message = "اطلاعات با موفیت ویرایش شد.";
}
else
{
message = "مشکلی در فرایند ویرایش اطلاعات ایجاد شده است.";
}
}
ViewBag.Message = message;
return View();
}
profile.cshtml
#model projectwebsite.Models.User
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.UserID)
<small class="text-muted">#Html.LabelFor(model => model.FirstName)</small>
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "form-text text-danger" })
<hr>
<small class="text-muted">#Html.LabelFor(model => model.LastName)</small>
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "form-text text-danger" })
<hr>
<small class="text-muted">#Html.LabelFor(model => model.DateOfBirth)</small>
#Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DateOfBirth, "", new { #class = "form-text text-danger" })
<button type="submit" value="Save" class="btn btn-success"> submit</button>
if (ViewBag.Message != null)
{
<div class="alert alert-danger">
<strong>error</strong>#ViewBag.Message
</div>
}
}
and last file user.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace projectwebsite.Models
{
[MetadataType(typeof(UserMetadata))]
public partial class User
{
public string Confirmpassword { get; set; }
}
public class UserMetadata
{
[Display(Name="نام")]
[Required(AllowEmptyStrings = false, ErrorMessage = "نام خود را وارد کنید.")]
public string FirstName { get; set; }
[Display(Name ="نام خانوادگی")]
[Required(AllowEmptyStrings = false, ErrorMessage ="نام خانوادگی را وارد کنید.")]
public string LastName { get; set; }
[Display(Name ="ایمیل")]
[Required(AllowEmptyStrings = false, ErrorMessage ="ایمیل خود را وارد کنید")]
[DataType(DataType.EmailAddress)]
public string EmailID { get; set; }
[Display(Name = "تاریخ تولد")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime DateOfBirth { get; set; }
[Display(Name = "پسورد")]
[Required(AllowEmptyStrings =false, ErrorMessage ="پسورد را وارد کنید.")]
[DataType(DataType.Password)]
[MinLength(6,ErrorMessage ="6 حرف کمترین طول پسورد میباشد.")]
public string Password { get; set; }
[Display(Name ="تکرار پسورد")]
[DataType(DataType.Password)]
[Compare("Password",ErrorMessage ="رمز عبور برابر نیست.")]
public string Confirmpassword { get; set; }
}
}
I've found an answer here: Entity Framework/MVC3: temporarily disable validation
By temporarily disabling validation I can bypass other properties validation check.

Json Result to List in ASP.net View

This is my form in contact class
<form method="POST">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="E-mail" name="subid" autofocus="">
</div>
<button href="" class="btn btn-gm btn-success">View</button>
</fieldset>
This is my code in controller and i have view called Contact
[HttpGet]
public ActionResult Contact()
{
return View();
}
[HttpPost]
public ActionResult Contact(string subid)
{
try
{
var webClient = new WebClient();
string url = string.Format(BASE_URL + "Subjectstatus/{0}", subid);
var json = webClient.DownloadString(url);
var js = new JavaScriptSerializer();
ViewBag.attendlist = js.Deserialize<List<attendlist>>(json);
return View();
}
catch
{
ViewBag.con = "gg";
return null;
}
}
This is my attendlist class
public class attendlist
{
[Display(Name = "ID")]
public string sid { get; set; }
[Display(Name = "Name")]
public string name { get; set; }
[Display(Name = "Subject")]
public string sub { get; set; }
[Display(Name = "Date")]
public string date { get; set; }
}
This is Contact View im trying to loop it using for each
#foreach (var dd in ViewBag.attendlist)
{
<h3>#dd.ID</h3>
}
This is the error when im try to load contact view
[HttpGet]
public ActionResult Contact()
{
return View( new ViewContact() );
}
[HttpPost]
public ActionResult Contact(ViewContact contact)
{
try
{
var webClient = new WebClient();
string url = string.Format(BASE_URL + "Subjectstatus/{0}", contact.subid);
var json = webClient.DownloadString(url);
var js = new JavaScriptSerializer();
attendlist list= js.Deserialize<attendlist>(json)
contact.attendlist = list;
return View(contact);
}
catch
{
ViewBag.con = "gg";
return null;
}
}
Class ViewContact
public class ViewContact
{
public attendlist list { get; set; }
public string subid { get; set; }
}
And the foreach at the view
foreach(var dd in Model.list){
//your html view code
}
The view
<form method="POST">
<fieldset>
<div class="form-group">
#Html.TextBoxFor(m => m.subid, new { #class = "form-control", #placeholder = "Email" }) >
</div>
<button href="" class="btn btn-gm btn-success">View</button>
</fieldset>
*Note textboxfor , get the model atributte and it bind later it correctly to the action submit
*Note that now you have to pass a contect not a string to Contact(ViewContact contact) action

Input Tag Returns Null to The Model int the Create ActionResult

In The entity like this I put the HttpPostedFileBase with the name ImageFile us virtual because I'm using mapping
public class Slider : IEntity
{
public virtual int Id { get; set; }
public virtual HttpPostedFileBase ImageFile { get; set; }
}
Here in the entity im getting entity.ImageFile = null so below the actions code
[HttpPost]
public ActionResult AddOrEdit(Slider entity)
{
try
{
string fileName = Path.GetFileNameWithoutExtension(entity.ImageFile.FileName);
string extension = Path.GetExtension(entity.ImageFile.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
entity.Image = fileName;
fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
entity.ImageFile.SaveAs(fileName);
if (ModelState.IsValid)
{
if (entity.Id == 0)
{
_sliderService.Insert(entity);
}
in the view i added the input tag with name ImageFile so normally I shouldn't get null ??
please help
#model Slider
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEdit", "Slider", FormMethod.Post, new { id =
"form", enctype = "multipart/form-data" , onsubmit = "return
SubmitForm(this)" }))
{
#Html.HiddenFor(m => m.Id)
<div class="form-group" style="height:270px;">
#Html.LabelFor(m => m.ImageFile, new { #class = "blue-text", #style =
"font-size:16px", #id = "" })
<input name="ImageFile" type="file" />
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
<input type="reset" value="Reset" class="btn" />
</div>
}
In order to get the file you can change the action params like this:
[HttpPost]
public ActionResult AddOrEdit(HttpPostedFileBase ImageFile,Slider slider)
{
....
}
but also you need to change your entity like this:
public class Slider : IEntity
{
public virtual int Id { get; set; }
public virtual string ImageUrl { get; set; }
}
then inside the action you can do:
if (ImageFile!= null)
{
slider.ImgUrl = SaveImage(ImageFile);
db.Slider.Add(slider);
db.SaveChanges();
}
and the SaveImage method:
private string SaveImage(HttpPostedFileBase uploadFile)
{
if (uploadFile != null && uploadFile.ContentLength > 0)
{
string relativePath = "~/Image/" + Path.GetFileName(uploadFile.FileName);
string physicalPath = Server.MapPath(relativePath);
uploadFile.SaveAs(physicalPath);
return uploadFile.FileName;
}
return null;
}
Thank you guys for your help , I solved it by removing" onsubmit = "return SubmitForm(this)" from the Html.BeginForm Tag , But in this case I'm not getting the Validation Messages or the notify messages any ideas ???
Below is the code of onsubmit
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
if ($(form).valid()) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
} else {
Popup.dialog('close');
$.notify(data.message, {
globalPosition: "top center",
className: "error"
})
}
}
});
}
return false;
}

Convert objects to JSON in C#

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; }
}

MVC4 Razor how to get selected value from dropdownlist?

My Model:
namespace mvc4deneme.Models
{
public class SiparisModel
{
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
[Display(Name = "Ürün Tipi")]
public Material UrunTipi { get; set; }
[Display(Name = "Yüzey")]
public Material Yuzey { get; set; }
public class Material
{
//public int? ID { get; set; }
public string ID { get; set; }
public string Name { get; set; }
}
}
MY CONTROLLER:
//my control page is SiparisController
public class SiparisController : Controller
{
//
// GET: /Siparis/
public ActionResult Index()
{
DataTable dt = null;
Material material = null;
var model = new SiparisModel();
List<Material> lstYuzey = new List<Material>{
new Material { ID = null, Name = "Seçiniz" },
new Material { ID = "D/-", Name = "Tek Yüz" },
new Material { ID = "D/D", Name = "Çift Yüz" } };
ViewBag.Yuzey = lstYuzey;
List<Material> lstUrunTipi = new List<Material> {
new Material { ID = null, Name = "Seçiniz" },
new Material { ID = "3100140", Name = "MKYL" },
new Material { ID = "3100180", Name = "FS.MKYL FA" },
new Material { ID = "3100190", Name = "FS.MKYL FC" },
new Material { ID = "3100090", Name = "YL" }, };
ViewBag.UrunTipi = lstUrunTipi;
return View(model);
}
}
MY Index.cshtml view page:
#using (Html.BeginForm())
{
#Html.DropDownListFor(x => x.SelectedValue, Model.Values)
<button type="submit">OK</button>
#Html.LabelFor(m => m.UrunTipi)
#Html.DropDownListFor(m => m.UrunTipi.ID,
new SelectList(ViewBag.UrunTipi, "ID", "Name"),
new { style = "width:310px" })
#Html.ValidationMessageFor(m => m.UrunTipi.ID) }
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.Yuzey)
#Html.DropDownListFor(m => m.Yuzey.ID,
new SelectList( ViewBag.Yuzey,"ID", "Name"),
new { style = "width:310px" })
#Html.ValidationMessageFor(m => m.Yuzey.ID)
}
My Ask:
How can i execute ok button to getting values of my UrunTipi and Yuzey selected values.
Thank you so much.
Regards,
B.Y.