No data saved in the partial view

asp.net-core-mvc entity-framework-core

Question

I'm trying to save data updated on the partial view called in parent Edit action. But the updated data is not saved.

I have a parent table 'Nz' and a child one 'Mkh' and trying to retrieve all the data of it in 'Nz' edit action as a partial view to let the user update it. The data is retrieved correctly but when the user update the data and press submit no data is saved! on the other hand, I want to retrieve 'Select' items with returned values not a normal text item.

This is my code:

//Nz model:
    public partial class Nz
    {
        public Nz()
        {
            Mkh = new HashSet<Mkh>();
        }
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:#########}")]
        public decimal TxtId { get; set; }
        public int Sn { get; set; }
        public string FullName { get; set; }
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
        public DateTime? BirthDate { get; set; }
        public int SexCode { get; set; }
        public string InsertUser { get; set; }
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
        public DateTime InsertDate { get; set; }

        public ICollection<Mkh> Mkh { get; set; }
    }
//Mkh Model:
    public partial class Mkh
    {
        public int Sn { get; set; }
        public decimal TxtId { get; set; }
        public int MkhCode { get; set; }
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
        public DateTime MkhDate { get; set; }
        public int Days { get; set; }
        public string Notes { get; set; }
        public string InsertUser { get; set; }
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
        public DateTime InsertDate { get; set; }


        public MkhType MkhCodeNavigation { get; set; }
        public Nz Txt { get; set; }
    }
//MkhType Model:
    public partial class MkhType
    {
        public MkhType()
        {
            Mkh = new HashSet<Mkh>();
        }

        public int MkhCode { get; set; }
        public string MkhName { get; set; }
        public string InsertUser { get; set; }
        public DateTime InsertDate { get; set; }

        public ICollection<Mkh> Mkh { get; set; }
    } 

Here is my context:

public partial class NozContext : DbContext
{
    public NozContext()
    {
    }

    public NozContext(DbContextOptions<NozContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Mkh> Mkh { get; set; }
    public virtual DbSet<MkhType> MkhType { get; set; }
    public virtual DbSet<Nz> Nz { get; set; }
    public virtual DbSet<Sex> Sex { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("Server=My-PC\\SQLEXPRESS;Database=Noz;Trusted_Connection=True;");
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        modelBuilder.Entity<Mkh>(entity =>
        {
            entity.HasKey(e => e.Sn);

            entity.ToTable("Mkh");

            entity.Property(e => e.Sn).HasColumnName("sn");

            entity.Property(e => e.Days).HasColumnName("days");

            entity.Property(e => e.InsertDate)
                .HasColumnName("insert_date")
                .HasColumnType("datetime")
                .HasDefaultValueSql("(getdate())");

            entity.Property(e => e.InsertUser)
                .IsRequired()
                .HasColumnName("insert_user")
                .HasMaxLength(20)
                .HasDefaultValueSql("(N'any')");

            entity.Property(e => e.MkhCode).HasColumnName("Mkh_code");

            entity.Property(e => e.MkhDate)
                .HasColumnName("Mkh_date")
                .HasColumnType("date");

            entity.Property(e => e.Notes).HasColumnName("notes");

            entity.Property(e => e.TxtId)
                .HasColumnName("txt_id")
                .HasColumnType("numeric(9, 0)");

            entity.HasOne(d => d.MkhCodeNavigation)
                .WithMany(p => p.Mkh)
                .HasForeignKey(d => d.MkhCode)
                .OnDelete(DeleteBehavior.ClientSetNull)
                .HasConstraintName("FK_Mkh_Mkh_type");

            entity.HasOne(d => d.Txt)
                .WithMany(p => p.Mkh)
                .HasForeignKey(d => d.TxtId)
                .OnDelete(DeleteBehavior.ClientSetNull)
                .HasConstraintName("FK_Mkh_Nz");
        });

        modelBuilder.Entity<MkhType>(entity =>
        {
            entity.HasKey(e => e.MkhCode);

            entity.ToTable("Mkh_type");

            entity.Property(e => e.MkhCode).HasColumnName("Mkh_code");

            entity.Property(e => e.InsertDate)
                .HasColumnName("insert_date")
                .HasColumnType("datetime")
                .HasDefaultValueSql("(getdate())");

            entity.Property(e => e.InsertUser)
                .IsRequired()
                .HasColumnName("insert_user")
                .HasMaxLength(20)
                .HasDefaultValueSql("(N'any')");

            entity.Property(e => e.MkhName)
                .IsRequired()
                .HasColumnName("Mkh_name")
                .HasMaxLength(50);
        });

        modelBuilder.Entity<Nz>(entity =>
        {
            entity.HasKey(e => e.TxtId);

            entity.ToTable("Nz");

            entity.Property(e => e.TxtId)
                .HasColumnName("txt_id")
                .HasColumnType("numeric(9, 0)");

            entity.Property(e => e.BirthDate)
                .HasColumnName("birth_date")
                .HasColumnType("date");


            entity.Property(e => e.InsertDate)
                .HasColumnName("insert_date")
                .HasColumnType("datetime")
                .HasDefaultValueSql("(getdate())");

            entity.Property(e => e.InsertUser)
                .IsRequired()
                .HasColumnName("insert_user")
                .HasMaxLength(20)
                .HasDefaultValueSql("(N'any')");

            entity.Property(e => e.SexCode).HasColumnName("sex_code");

            entity.Property(e => e.Sn)
                .HasColumnName("sn")
                .ValueGeneratedOnAdd();

            entity.HasOne(d => d.SexCodeNavigation)
                .WithMany(p => p.Nz)
                .HasForeignKey(d => d.SexCode)
                .OnDelete(DeleteBehavior.ClientSetNull)
                .HasConstraintName("FK_Nz_sex");
        });

        modelBuilder.Entity<Sex>(entity =>
        {
            entity.HasKey(e => e.SexCode);

            entity.ToTable("sex");

            entity.Property(e => e.SexCode).HasColumnName("sex_code");

            entity.Property(e => e.SexName)
                .IsRequired()
                .HasColumnName("sex_name")
                .HasMaxLength(10);
        });

        modelBuilder.Entity<Nz>()
        .HasAlternateKey(x => x.Sn).HasName("IX_Sn");
    }
}

and the NzController actions:

public class NzController : Controller
{
    private readonly NozContext _context;

    public NzController(NozContext context)
    {
        _context = context;
    }
// ........ Some Code here .............
public async Task<IActionResult> Edit(decimal? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        //var Nz = await _context.Nz.FindAsync(id);
        var Nz = await _context.Nz
                     .Include(n => n.Mkh)
                     .ThenInclude(m => m.MkhCodeNavigation)
                     .FirstOrDefaultAsync(n => n.TxtId == id.Value);
        if (Nz == null)
        {
            return NotFound();
        }
        ViewData["SexCode"] = new SelectList(_context.Sex, "SexCode", "SexName", Nz.SexCode);
        return View(Nz);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(decimal id, [Bind("TxtId,Sn,FullName,BirthDate,SexCode,InsertUser,InsertDate")] Nz Nz)
    {
        if (id != Nz.TxtId)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                var Edited = new Nz()
                {
                    TxtId = Nz.TxtId,
                    BirthDate = Nz.BirthDate,
                    InsertDate = Nz.InsertDate,
                    InsertUser = Nz.InsertUser,
                    FullName = Nz.FullName,
                    SexCode = Nz.SexCode,
                    Mkh = Nz.Mkh.Where(m => m.TxtId == Nz.TxtId).ToList(),
                };
                _context.Update(Edited);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!NzExists(Nz.TxtId))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        ViewData["SexCode"] = new SelectList(_context.Sex, "SexCode", "SexName", Nz.SexCode);
        return View(Nz);
    }

the partial view 'EditNz':

@model IEnumerable<Mkh>

<h4>MkhTbl</h4>
<hr />
    <table class="table">
        <thead>
            <tr>
                <th>
                    Date
                </th>
                <th>
                    Days
                </th>
                <th>
                    Notes
                </th>
                <th>
                    Mkh Type
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {

                <tr>
                    <td> 
                        @Html.EditorFor(modelItem => item.MkhDate)
                    </td>
                    <td>
                        @Html.EditorFor(modelItem => item.Days)
                    </td>
                    <td>
                        @Html.EditorFor(modelItem => item.Notes)
                    </td>
                    <td>
                        @Html.EditorFor(modelItem => item.MkhCodeNavigation.MkhName)
                    </td>
                </tr>
            }
        </tbody>
    </table>

    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    } 

and the calling of the previous partial in Edit view in NzController:

@model NozCoreWebApp5.Models.Nz
@*@{
        ViewData["Title"] = "Edit";
    }*@

<form asp-action="Edit">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <input type="hidden" asp-for="TxtId" />
    <input type="hidden" asp-for="InsertDate" />
    <input type="hidden" asp-for="InsertUser" />

    <hr />


    <div class="row">
        <div class="col-md-3">
            <label asp-for="FullName" class="control-label">Full Name</label>
            <input asp-for="FullName" class="form-control" readonly/>
            <span asp-validation-for="FullName" class="text-danger"></span>
        </div>
        <div class="col-md-3">
            <label asp-for="BirthDate" class="control-label">Birth Date</label>
            <input asp-for="BirthDate" class="form-control" readonly/>
            <span asp-validation-for="BirthDate" class="text-danger"></span>
        </div>
        <div class="col-md-3">
            <label asp-for="SexCode" class="control-label">Sex</label>
            <select asp-for="SexCode" class="form-control" asp-items="ViewBag.SexCode"></select>
            <span asp-validation-for="SexCode" class="text-danger"></span>
        </div>
    </div>

    <br />
    <div class="form-group">
        <input type="submit" value="Save" class="btn btn-default" />
    </div>
</form>
<div>
    <a asp-action="Index">Nz List</a>
</div>

@{ await Html.RenderPartialAsync("~/Views/Mkhalfa/EditNz.cshtml", Model.Mkh); }

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Now when I press save button (submit) no data is saved for the partial one like days! Why? and How to solve please?

and How to return Select with returned values from MkhType? (using MkhCodeNavigation I think)

This is what happen when I put a breakpoint in the Edit method at 'Edited' var and trying to update the 'days' field in the partial: Post Edit Method

as you notice Edited var is null. does that mean no data passed to the controller? how to solve?

1
1
2/2/2019 7:25:50 AM

Accepted Answer

Just realized what you did....

public async Task<IActionResult> Edit(decimal id, [Bind("TxtId,Sn,FullName,BirthDate,SexCode,InsertUser,InsertDate")] Nz Nz)

What's missing here is Mkh from the binding list, e.g. not bound not filled. Hence the empty results. You can keep the binding but need to add in Mkh to the list

public async Task<IActionResult> Edit(decimal id, [Bind("TxtId,Sn,FullName,BirthDate,SexCode,Mkh,InsertUser,InsertDate")] Nz Nz)

One other thing your current setup doesn't allow for multi-entries into the Mkh collection, except for 1 at a time. Save and repeat, reload page from another Edit. Mkh saves might run into graph issues with EF as well.. But i think you have accounted for it with the relationships that you have setup.

0
2/3/2019 10:00:38 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow