1

I am developing an administration page in ASP.NET MVC.

But I have a problem when I edit the film.

When I edit a movie, the sessions appear on my page. And I can remove them. If I click on edit without removing anything, I get the values ​​well. But when I remove the first session, my array is null. When I remove the second session, the array comes with this value.

Does anyone know why?

My code:

Edit.cshtml

@using (Html.BeginForm("Edit", "Trans", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.ID, htmlAttributes: new { @id = "id" })
    @Html.HiddenFor(model => model.Selected, htmlAttributes: new {  })

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

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

    <div class="form-group">
        @Html.LabelFor(model => model.Selected, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Selected, new SelectList(Model.tipos, "ID", "Tipo", Model.Selected), htmlAttributes: new { @id = "ddldropdown", @class = "form-control", @disabled = "disabled" })
            @Html.ValidationMessageFor(model => model.Selected, "", new { @class = "text-danger" })
        </div>
    </div>

    <div id="partialDiv">

    </div>

    <div id="CinemaDiv" style="display:none">
        @Html.Partial("Edit_Cinema", Model)
    </div>


    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Edit" id="Save" class="btn btn-default" onclick="Fillarrays()" />
        </div>
    </div>


</div>
}


@section Scripts {

    <script type="text/javascript">
        //Script para adicionar os Views da pasta Outros no div "partialDiv"
        $(document).ready(function () {
            var txt = $("#ddldropdown option:selected").text();
            var id = $("#id").val();

                    $.ajax({
                        type: 'get',
                        url: '/Outros/Edit_Cinema' + '/' + id,
                        dataType: 'html',
                        success: function (html) {
                            $('#partialDiv').html(html);
                        }
                    });
    </script>


    @*< !--Script Cinema (Partial View)-- >*@
    <script type="text/javascript">
           
            //funcao para remover o campo sessao
            function rmSessao(id) {
                $('#sessao_' + id + '').remove();
            }
    </script>


    <script type="text/javascript">
        $('#Save').click(function () {
            var form = $("#formH");
            var url = form.attr("action");
            var formData = form.serialize();
            $.post(url, formData, function (data) {
                $("#msg").html(data);

                //Script para adicionar os campos das partial views

                var txt = $("#ddldropdown option:selected").text();
                var frm = $("form");
                var data = new FormData($("form")[0]);

                    $.ajax({
                        url: '/Outros/Edit_Cinema' + '/' + id,
                        type: "POST",
                        processData: false,
                        data: data,
                        dataType: 'html',
                        contentType: false,
                    });
     }
    </script>
}

Edit_Cinema.cshtml

@model ProjetoFinal.Models.ItemViewModel

<div class="form-horizontal">
        @*@Html.ValidationSummary(true, "", new { @class = "text-danger" })*@
        @Html.HiddenFor(model => model.Cinema.ID)


        @Html.LabelFor(model => model.Cinema.Sessoes, htmlAttributes: new { @class = "control-label col-md-2" })

    <div class="form-group">
        @for (int i = 0; i < Model.Cinema_array_Sessoes_Edit.Count; i++)
        {
            <div class="col-md-10" style="margin-left:195px;margin-bottom:10px" id="sessao_@i">
                <div class="input-group">
                    <span class="input-group-btn">
                        @Html.EditorFor(model => Model.Cinema_array_Sessoes_Edit[i], new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => Model.Cinema_array_Sessoes_Edit[i], "", new { @class = "text-danger" })
                        <input type="button" class="btn btn-primary" id="com" value="-" onclick="rmSessao(@i)" />
                    </span>
                </div>
            </div>
        }

    </div>

</div>

Models

ItemViewModel

public class ItemViewModel
{
    public int ID { get; set; }

    [Display(Name = "Tipo", ResourceType = typeof(Resource))]
    //public List<Tipo> tipos { get { return Services.GetTypes(); } } get all types
    public List<Tipo> tipos { get; set; }

    [Display(Name = "Tipo", ResourceType = typeof(Resource))]
    public int? Selected { get; set; }

    #region Cinema
    public Cinema Cinema { get; set; }
    public string[] Cinema_array_sessoes { get; set; }
    [Display(Name = "Cinema_array_Sessoes_Edit")]
    public List<DateTime?> Cinema_array_Sessoes_Edit { get; set; }
    public string[] array_Sessoes_Edit { get; set; }
    public string[] array_sessoes { get; set; }
    #endregion


    public ItemViewModel()
    {
        tipos = new List<Tipo>();
        
        Cinema = new Cinema();

        #region For the cinema
        Cinema_array_Sessoes_Edit = new List<DateTime?>();
        #endregion

        //vai buscar os tipos para aparecer no dropdown
        tipos = Services.GetTypes();
    }

    public class TransmontanosDBContext : DbContext
    {
        public DbSet<Item> Transmontanos { get; set; }
    }
}

TransController.cs

 public class TransController : Controller
{   
    [HttpPost]
        public ActionResult Edit(ItemViewModel item, string Latitude, string Longitude)
        {
            Item obj = new Item();
            if (item.Titulo != null)
            {
                obj.ID=item.ID;
                obj.Titulo = item.Titulo;
                obj.Descricao = item.Descricao;
                obj.Localidade = item.Localidade;
                obj.Endereco = item.Endereco;
                obj.Latitude =Latitude;
                obj.Longitude = Longitude;
                obj.Selected = item.Selected;

                if (item.Main_Image != null)
                {
                    if (item.Main_Image.ContentLength != 0)
                    {
                        //Adiciona a imagem principal à pasta Images
                        var pathMain = Path.Combine(Server.MapPath("~/Images/"), obj.ID + ".jpg");
                        item.Main_Image.SaveAs(pathMain);

                        //Adiciona a imagem principal no ultimo item inserido
                        Services.AddImage_ToItem(obj.ID);
                    }
                }

                Services.EditObject(obj);

                return RedirectToAction("Index", "Trans");
            }

            return View(item);

        }
}

OutrosController.cs

 public class OutrosController : Controller
 {
        [HttpPost]
        public ActionResult Edit_Cinema(ItemViewModel item)
        {
            Cinema cinema = new Cinema();
            cinema = item.Cinema;
        }
}

Results:

Sessions in my movie when I click edit

enter image description here

When I do not remove any of the fields

enter image description here

When I remove the second field

enter image description here

When I remove the first field (Problem)

enter image description here

3
  • 1
    Hello, that's a lot of code. You would get more answers if you reduce your code to a Minimal, Reproducible Example Commented Dec 30, 2020 at 17:40
  • Which way do you remove session fields? Commented Dec 30, 2020 at 17:41
  • @Sergey Hi. I just remove the div. Is my function rmSession Commented Dec 30, 2020 at 17:58

1 Answer 1

2

I would change your view code to this:

  @for (int i = 0; i < Model.Cinema_array_Sessoes_Edit.Count; i++)
        {
            <div class="col-md-10" style="margin-left:195px;margin-bottom:10px" id="sessao_@i">
                <div class="input-group">
                    <span class="input-group-btn">
                        @Html.EditorFor(model => Model.Cinema_array_Sessoes_Edit[i], new { htmlAttributes = new { @class = "form-control" @id="id_@i" } })
                        @Html.ValidationMessageFor(model => Model.Cinema_array_Sessoes_Edit[i], "", new { @class = "text-danger" })
                        <input type="button" class="btn btn-primary" id="com" value="-" onclick="rmSessao(@i)" />
                    </span>
                </div>
            </div>
        }

Change your delete javascript function:

/funcao para remover o campo sessao
            function rmSessao(id) {
                $('#id_' + id + '').val(null); //assingn null to date value
                 $('#sessao_' + id + '').addClass("d-none"); // just hide it
            }

And change your controller action:

 public ActionResult Edit_Cinema(ItemViewModel item)
        {
              
           item.Cinema_array_Sessoes_Edit.RemoveAll(x => x== null);

.... //your code
// you don't need it at all - Cinema cinema = new Cinema();
            var cinema = item.Cinema;
        }
Sign up to request clarification or add additional context in comments.

2 Comments

Happy New Year!
Happy New Year for you too

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.