Calculation of hotel rates in MVC application

4

Recently I started programming in MVC and I'm full of doubts.

I'm developing a hotel reservation system and after spending 3 days trying to calculate the total cost of an unsuccessful reservation, I've decided to ask for help with the code because I'm in doubt if I'm creating Controller and Views correctly.

In this system I have registered 4 different hotels, each hotel has several types of rooms and each room has a different daily rate, these rates vary according to the period of the year (seasons) and are calculated based on an initial and final date, whether the day falls on a Friday or a Saturday, whether the reservation is for a week or a month.

That is, I need to calculate the day by day between the date of arrival and the date of departure, check if the day is within a season and whether it is Friday or a Saturday, etc. and at the end have the full price of the reservation.

The registration of hotels, room types, seasons (low season, Christmas, summer, winter, Easter, etc.) work perfectly to the point where a Calcular reserva button is called. I can not make the calculation nor return some View showing the Reserve Total . Here is the code:

Classes:

public class Hotel
{
    public int HotelId { get; set; }
    public string Nome { get; set; }
    public virtual ICollection<Quarto> Quarto { get; set; }
}

public class Quarto
{
    public int QuartoId { get; set; }
    public string Nome { get; set; }
    [DataType(DataType.Currency)]
    public int HotelId { get; set; }

    public virtual Hotel Hotel { get; set; }
    public virtual ICollection<Temporada> Temporada { get; set; }
}

public class Temporada
{
    public int TemporadaId { get; set; }
    public string NomeTemporada { get; set; }

    public DateTime Chegada { get; set; }

    public DateTime Saida { get; set; }

    [Display(Name = " Diaria Fora de Temporada")]
    public decimal DiariaForaTemporada{ get; set; }

    [Display(Name = "$ Diaria Temporada ")]
    public decimal DiariaTemporada { get; set; }

    [Display(Name = "$ Diaria Sexta/Sabado")]
    public decimal DiariaSabado { get; set; }

    [Display(Name = "$ Diaria Semana")]
    public decimal Diaria Semana { get; set; }

    [Display(Name = "$ Diaria Mes")]
    public decimal DiariaMes { get; set; }

    public int QuartoId { get; set; }

    public int HotelId { get; set; }

    public virtual Hotel Hotel { get; set; }
    public virtual Quarto Quarto { get; set; }
}

Controller:

// GET: Admin/Temporada

public ActionResult TotalReserva()
{
    return View();
}

// POST: Admin/Temporada
[HttpPost]
[ValidateAntiForgeryToken]
public ViewResult ValorDiaria(Temporada TotalReserva)
{
    var dChegada = new DateTime(Chegada);
    var dSaida = new DateTime(Saida);
    var vlrdiaria = 0;

    for (var curData = dChegada; curDate < dSaida; curDate = curDate.AddDays(1))
    {
        vlrdiaria += Convert.ToInt32(ValorDiaria(curDate));
    }

    return View(TotalReserva);
}

private ViewResult View(Func<ViewResult> ValorDiaria)
{
    throw new NotImplementedException();
}

public static int ValrDiaria(DateTime Date)
{
    var temporada = new List<Temporada>();

    foreach (var temporada in temporadas)

    if (temporada.ContainsDate(Date))
    {

        if (Date.DayOfWeek == DayOfWeek.Sexta) || (Date.DayOfWeek == DayOfWeek.Sexta)
        {
            return Convert.ToInt32(temporada.DiariaSabado);
        }
        else
        {
            return Convert.ToInt32(temporada.DiariaTemporada);
        }
    }
    return Convert.ToInt32(temporada.DiariaBasica;
}
    
asked by anonymous 17.12.2015 / 05:12

1 answer

1

There are several errors in your code, but I imagine you need a calculation routine in Ajax. I put this context proof to help .

First, set a ReservasViewModel :

public class ReservasViewModel
{
    public int QuartoId { get; set; }
    public DateTime DataChegada { get; set; }
    public DateTime DataSaida { get; set; }
    public Decimal ValorReserva { get; set; }
}

Next, a Controller with an initial Action , just to view a View of this ViewModel: p>

public class ReservasController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: Reservas
    public ActionResult Index()
    {
        ViewBag.Quartos = db.Quartos.ToList();
        return View();
    }

    ...
}

A View :

@model ExemploAjax.ViewModels.ReservasViewModel
@using ExemploAjax.Models

<h1>Reservas</h1>


<div class="form-group">
    @Html.LabelFor(model => model.QuartoId, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.QuartoId, ((IEnumerable<Quarto>)ViewBag.Quartos).Select(q => new SelectListItem
       {
           Text = q.Nome,
           Value = q.QuartoId.ToString(),
           Selected = (Model != null) && (Model.QuartoId == q.QuartoId)
       }), "Selecione...", new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.QuartoId, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.DataChegada, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.DataChegada, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.DataChegada, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.DataSaida, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.DataSaida, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.DataSaida, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.ValorReserva, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.ValorReserva, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
        @Html.ValidationMessageFor(model => model.ValorReserva, "", new { @class = "text-danger" })
    </div>
</div>

<button id="Calcular">Calcular</button>

@section Scripts {
    <script>
        $(document).ready(function () {
            $("#Calcular").click(function () {
                $.ajax({
                    url: "@Url.Action("CalcularReserva", "Reservas")",
                    type: 'POST',
                    data: {
                        DataSaida: $("#DataSaida").val(),
                        DataChegada: $("#DataChegada").val(),
                        QuartoId: $("#QuartoId").val()
                    },
                    success: function (result) {
                        $("#ValorReserva").val(result.ValorReserva);
                    }
                });
            });
        });
    </script>
}

Notice that I call an Ajax method by clicking the "Calculate" button:

$(document).ready(function () {
    $("#Calcular").click(function () {
        $.ajax({
            url: "@Url.Action("CalcularReserva", "Reservas")",
            type: 'POST',
            data: {
                DataSaida: $("#DataSaida").val(),
                DataChegada: $("#DataChegada").val(),
                QuartoId: $("#QuartoId").val()
            },
            success: function (result) {
                $("#ValorReserva").val(result.ValorReserva);
            }
        });
    });
});

For this call, you need to create a method in the controller ReservasController like this:

    public JsonResult CalcularReserva(ReservasViewModel viewModel)
    {
        var dChegada = viewModel.DataChegada;
        var dSaida = viewModel.DataSaida;
        var vlrdiaria = 0;

        for (var curDate = dChegada; curDate < dSaida; curDate = curDate.AddDays(1))
        {
            vlrdiaria += Convert.ToInt32(ValorDiaria(curDate));
        }

        return Json(new { ValorReserva = vlrdiaria }, JsonRequestBehavior.AllowGet);
    }

    private static int ValorDiaria(DateTime Date)
    {
        if ((Date.DayOfWeek == DayOfWeek.Friday) || (Date.DayOfWeek == DayOfWeek.Saturday))
        {
            return 100;
        }

        return 80;
    }

Also note that I put a simplified version of ValorDiaria because your version does not make sense.

    
21.12.2015 / 21:07