C#将英尺和英寸保存为小数

时间:2016-11-06 23:29:57

标签: c# asp.net-mvc entity-framework asp.net-mvc-4 c#-4.0

经过两天的困惑并尝试了许多不同的方式后,我不情愿地来这里寻求一些建议(不情愿,因为我觉得我应该这样做了)。

我正在尝试将英尺和英寸值保存为小数。

我允许用户输入以英尺和英寸为单位的房间宽度,并尝试将其转换为小数值。

如果我输入width feet: 10 width inches: 10我希望将330.2保存到我的数据库,那么当我重新加载页面时,我希望width feet: 10 width inches: 10成为显示。

我的问题是,在我的viewmodel中,我尝试为每个房间的WidthImperial分配一个值,但它设置为[0] = 108333.0[1] = 4.0。没有任何内容保存到数据库,因为此问题导致Width参数超出范围。

我做错了什么,对任何帮助都很熟悉。

我正在使用asp mvc 4和实体框架。

我的代码

Rooms.cshtml

@Html.TextBoxFor(m => m.Rooms[i].WidthImperial[0], null, new { @class = "form-control", @placeholder = "Width ft" })
@Html.TextBoxFor(m => m.Rooms[i].WidthImperial[1], null, new { @class = "form-control", @placeholder = "Width inches" })

MyController.cs

[HttpPost]
public ActionResult TakeOn(TakeOn to)
{
    ...Other Stuff
    properties = Session["properties"] as List<Property>;
    _Property = properties.FirstOrDefault(p => p.PropertyID == to.PropertyID);
    _Property = to.MapToProperty(_Property, UOW);
    ...Other stuff
}

ViewModel.cs

public class TakeOn
{
    public List<Room> Rooms { get; set; }

    //maps the view model to the property class
    public BL.Property MapToProperty(BL.Property property, UnitOfWork uow)
    {
        ...some other stuff
        property.Rooms = SetRooms(property);
        ...some other stuff
    }

    ICollection<Room> SetRooms(BL.Property property)
    {
        foreach (Room rm in this.Rooms)
        {
            if (!string.IsNullOrEmpty(rm.Title) || rm.Images.Count > 0)
            {
                Room room = property.Rooms.FirstOrDefault(r => r.RoomID == rm.RoomID);//get room if it exists in db
                if (room == null)
                {
                    room = new Room();//create new room and add to property
                    room.Images = new List<BL.Image>();
                    property.Rooms.Add(room);
                }

                room.WidthImperial = thisRoom.WidthImperial;
             }
         }
    }
}

Room.cs(EF模型)

public partial class Room
{
    ...other properties
    public Nullable<decimal> Width { get; set; }
    ...other properties
}

Room.cs(附加属性)

public partial class Room
{
    public List<double> WidthImperial
    {
        get
        {
            double centimetres = Convert.ToInt32(this.Width * 100);
            double totalInches = Convert.ToInt32(Math.Round(centimetres / 2.54)); // This will take a floor function of Centimetres/2.54
            double feet = (totalInches - totalInches % 12) / 12; // This will make it divisible by 12
            double inches = totalInches % 12; // This will give you the remainder after you divide by 12
            return new List<double> { feet, inches };
        }
        set
        {
            //convert value to inches
            double feet = value[0];
            double inches = value[1];
            inches += feet * 12;
            this.Width = (decimal)inches * 2.54m;
        }
    }
}

0 个答案:

没有答案