Calculation of hotel nights in MVC application

Asked

Viewed 668 times

4

I recently started programming in MVC and I am full of doubts.

I’m developing a hotel reservation system and after spending 3 days trying to calculate the total cost of a reservation unsuccessfully, I decided to ask for help with the code because I’m wondering if I’m creating the Controller and the Views correctly.

In this system I have registered 4 different hotels, each hotel has several room types and each room has a different daily rate, and these rates vary depending on the period of the year (seasons) and are calculated on the basis of an initial and final date, whether the day falls on a Friday or a Saturday, whether the reservation is for a week or for 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 if it is Friday or a Saturday, etc. and at the end have the total 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 button Calcular reserva is called.
I’m not able to do the calculation or return any View showing the Total Reserve. Follows 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;
}
  • Your code should not even run, you have syntax error in the penultimate line Convert.Toint32(season.Diariabasica; @Jose Silveira

  • The syntax error happened at the time of posting the question. In the application it is correct. Anyway, thank you for your answer.

  • I don’t understand what the difficulty is. Here: vlrdiaria += Convert.ToInt32(ValorDiaria(curDate));, this value is computed but goes nowhere.

  • I cannot return any value and consequently get the total value of the reservation. I need to calculate day by day, identifying if the value for the day is basic daily, daily Thursday or Friday or daily fimdesemana and then add up everything, I think much of the code is wrong. But unfortunately I’m not able to identify these errors.

1 answer

1

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

First of all, define 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; }
}

After, a Controller with a Action initial, only to display a View of this Viewmodel:

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

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

    ...
}

To 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":

$(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 thus:

    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 makes no sense.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.