how to save dimension of a div into mvc4 database table - asp.net-mvc

This is my model to save the div width and height which i want to save this in decimal value when i am resizing div in view
Eg :50.178
but it is saving 50
public decimal FormElementWidth { get; set; }
public decimal FormElementHeight { get; set; }
This is my Controller class
public void UpdateFormElementDimension(long formElementId, int elementWidthPercent, int elementHeightPercent)
{
//long userId = WebSecurity.GetUserId(User.Identity.Name);
FormElement formElement = db.FormElements.Find(formElementId);
formElement.FormElementWidth = elementWidthPercent;
formElement.FormElementHeight = elementHeightPercent;
db.Entry(formElement).State = EntityState.Modified;
db.SaveChanges();
}
so how i can save this decimal value when resizing div in view?

use float Attribute in your model and when posting the value parse your value in float as below
float myDecimalValue = float.Parse(yourValue);

but it is saving 50
That's because UpdateFormElementDimension()'s parameters elementWidthPercent and elementHeightPercent parameters are of type int.
You most likely want them to be decimal.
You could've found this out by putting a breakpoint inside the method and inspect the variables' content.

Related

dynamically generating json from json for highcharts heap map chart using ajax

i have data in my datatable (c#), i plan to send the data to the JS so that highcharts heatmap can understand and plot the heatmap.
following is the structure of datatable (c#)
xaxis yaxis value color
0 0 50 green
0 1 60 yellow
1 0 66 red
1 1 60 yellow
i want json in the below format so that highchart can understand
[
{x:0,y:0,value:50,color:'green'},
{x:0,y:1,value:60,color:'yelow'},
{x:1,y:0,value:66,color:'red'},
{x:1,y:1,value:50,color:'green'}
]
please help me in getting the desired output.once i get the desired output i will set to the chart using
chart.series[0].setdata(jsondata);
Left out code and error handling but I think this is sort of what you are looking for.
/// <summary>
/// serializable class that represent one data point
/// </summary>
[Serializable()]
class heatmap
{
public int x { get; set; }
public int y { get; set; }
public int value { get; set; }
public string color { get; set; }
/// <summary>
/// Use a public static function to copy data from the data table
/// to the list object
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public static List<heatmap> createHeatMap(ref DataTable table)
{
List<heatmap> list = new List<heatmap>();
foreach(DataRow row in table.Rows)
{
heatmap map = new heatmap();
map.x = Convert.ToInt32(row["x"]);
map.y = Convert.ToInt32(row["y"]);
map.value = Convert.ToInt32(row["value"]);
map.color = Convert.ToString(row["color"]);
list.Add(map);
}
return list;
}
}
// your code that populates the datatable
//blah blah blah
List<heatmap> map = heatmap.createHeatMap(ref datatable);
// I use newtonsoft for serialization
string jsonMap = Newtonsoft.Json.JsonConvert.SerializeObject(map);
return jsonMap;

How to pass value from one action to another action having same controller

Hi I am developing an application in MVC3. and i am stuck at one place. Everytime when control goes to IIndex1 action its argument value has become 0. But it should be same as value in IIndex action argument. I have used session, ViewBag, ViewData but my problem is remains. Please suggest me.
public ActionResult GetMDN(string msisdn)
{
number = msisdn.Substring(0, msisdn.IndexOf('$'));
if (number.ToLower() != "unknown" && number.Length == 12)
{
number = number.Remove(0, 2);
}
Session["msdresponse"] = number;
Session["moptr"] = msisdn.Substring(msisdn.LastIndexOf('$') + 1);
number = msisdn;
int sngid=int.Parse(ViewData["isongid"].ToString());
return RedirectToAction("IIndex1", new { iid = sngid });
}
public ActionResult IIndex(int id)
{
ViewBag.isongid = id;
ViewData["isongid"] = id;
Response.Redirect("http:XXXXXXXXXXXXXXXX");
return RedirectToAction("GetMDN");
}
public ActionResult IIndex1(int iid)
{
}
You can use TempData.You can pass every types of data between to action, whether they are in same controller or not. Your code should be something like it:
public ActionResult GetMDN(string msisdn)
{
int sngid=10;
TempData["ID"] = sngid;
return RedirectToAction("IIndex");
}
public ActionResult IIndex()
{
int id = Convert.ToInt32(TempData["ID"]);// id will be 10;
}
Use TempData instead of ViewData/ViewBag to store data that should persist after redirect.
ViewData/ViewBag allow to pass value from controller to view.
Something to read on this subject:
http://www.codeproject.com/Articles/476967/WhatplusisplusViewData-cplusViewBagplusandplusTem
http://msdn.microsoft.com/en-us/library/dd394711(v=vs.100).aspx
you can use TempData["name"] = variableToPass;

How to sort Vectors in blackberry using SimpleSortingVector?

I am having trouble to sort Vector for my blackberry app using SimpleSortingVector. My stuff does not sort it remains the same.
here is what i have so far...
MyComparator class
private Vector vector = new Vector(); //Assume that this vector is populated with elements already
SimpleSortingVector ssv = new SimpleSortingVector();
ssv.setSortComparator(new Comparator() {
public int compare(Object o1, Object o2) {
Record o1C = (Record)o1;
Record o2C = (Record)o2;
return o1C.getName().compareTo(o2C.getName());
}
public boolean equals(Object obj) {
return compare(this, obj) == 0;
}
});
for(int i=0;i<vector.size();i++){
Record record = new Record();
record=(Record) vector.elementAt(i);
//when you add elements to this vector, it is to post to be automatically sorted
ssv.addElement(record);
}
class Record
public class Record {
String name;
int price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
SimpleSortingVector does not sort by default. This was unexpected for me the first time I ran into it, too, given the name of the class.
You can do one of two things. Call SimpleSortingVector.setSort(true) to make sure the vector is always sorted after each change. This is surprisingly not turned on by default.
Or, you can call SimpleSortingVector.reSort() after adding all the elements to the vector, to do the sort in one batch operation.

Dynamic DBSet lookup and query

I have a partial result view that takes in the name of the table and a value for a particular column to query. I read the DBContext API and found that Set(Type) should return a DBSet that you can do CRUD operations on. I don't know how exactly to query the DBSet without a PK since the user don't know the PK to look up.
May be using Classic ADO would be easier?
EDIT: I figure out how to use DbSet.SQLQuery function but have no clue to store the results. I inspected the element in debugger and the SQLQuery does work as it found all the rows inside the table.
public class SF1DB : DbContext
{
//List of table names that feeds a DropDownList
public DbSet<tablelist> tables { get; set; }
//Data table
public DbSet<dataTable1> dataTable1 { get; set; }
public DbSet<dataTable2> dataTable2 { get; set; }
//...list of other tables
}
public PartialViewResult GetFeatures(String tablelist, String[] countyfp)
{
String type = "MvcApplication1.Models." + tablelist;
Type dbType = Type.GetType(type);
DbSet set = _db.Set(dbType);
String sql = "select * from " + tablelist;
//How do I store the result in a variable?
set.SqlQuery(sql);
return PartialView();
}
I figured it out by creating a List that have the same type as the DbSet that the user selected. Then I use the SQLQuery's GetEnumerator method and iterate thru the result and add to the new list. Finally, pass the list to the partial view.
public PartialViewResult GetFeatures(String tablelist, String[] countyfp)
{
String type = "MvcApplication1.Models." + tablelist;
Type dbType = Type.GetType(type);
DbSet set = _db.Set(dbType);
String sql = "select * from " + tablelist + " where ";
Type listType = typeof(List<>).MakeGenericType(dbType);
IList list = (IList)Activator.CreateInstance(listType);
for (int i = 0; i < countyfp.Length; i++)
{
sql += "cntyidfp like '%" + countyfp[i] + "'";
if (i < (countyfp.Length - 1))
{
sql += " or ";
}
}
IEnumerator result = set.SqlQuery(sql).GetEnumerator();
while (result.MoveNext())
{
list.Add(result.Current);
}
return PartialView(list);
}

MVC3 DataAnnotationsExtensions error using numeric attribute

I've installed Scott's Kirkland DataAnnotationsExtensions.
In my model I have:
[Numeric]
public double expectedcost { get; set; }
And in my View:
#Html.EditorFor(model => model.expectedcost)
Now, when the page tries to render I get the following error:
Validation type names in unobtrusive
client validation rules must be
unique. The following validation type
was seen more than once: number
Any ideas why I'm getting the error ?
The quick answer is simply remove the attribute
[Numeric]
The longer explanation is that by design, validation already adds a data-val-number because it's of type double. By adding a Numeric you are duplicating the validation.
this works:
[Numeric]
public string expectedcost { get; set; }
because the variable is of type string and you are adding the Numeric attribute.
Hope this helps
I basically had the same problem and I managed to solve it with the following piece of code: (As answered here: ASP.NET MVC - "Validation type names must be unique.")
using System;
using System.Web.Mvc;
And the ValidationRule:
public class RequiredIfValidationRule : ModelClientValidationRule
{
private const string Chars = "abcdefghijklmnopqrstuvwxyz";
public RequiredIfValidationRule(string errorMessage, string reqVal,
string otherProperties, string otherValues, int count)
{
var c = "";
if (count > 0)
{
var p = 0;
while (count / Math.Pow(Chars.Length, p) > Chars.Length)
p++;
while (p > 0)
{
var i = (int)(count / Math.Pow(Chars.Length, p));
c += Chars[Math.Max(i, 1) - 1];
count = count - (int)(i * Math.Pow(Chars.Length, p));
p--;
}
var ip = Math.Max(Math.Min((count) % Chars.Length, Chars.Length - 1), 0);
c += Chars[ip];
}
ErrorMessage = errorMessage;
// The following line is where i used the unique part of the name
// that was generated above.
ValidationType = "requiredif"+c;
ValidationParameters.Add("reqval", reqVal);
ValidationParameters.Add("others", otherProperties);
ValidationParameters.Add("values", otherValues);
}
}
I hope this helps.

Resources