1

I have two linked models in an ADO.NET Entity Data Model.

AspNetUsers

    public partial class AspNetUsers
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public AspNetUsers()
    {
        this.UserVacations = new HashSet<UserVacations>();
        this.UserSicknesses = new HashSet<UserSicknesses>();
    }
    public string Id { get; set; }
    public string Email { get; set; }
    public bool EmailConfirmed { get; set; }
    public string PasswordHash { get; set; }
    public string SecurityStamp { get; set; }
    public string PhoneNumber { get; set; }
    public bool PhoneNumberConfirmed { get; set; }
    public bool TwoFactorEnabled { get; set; }
    public Nullable<System.DateTime> LockoutEndDateUtc { get; set; }
    public bool LockoutEnabled { get; set; }
    public int AccessFailedCount { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<UserVacations> UserVacations { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<UserSicknesses> UserSicknesses { get; set; }
}

and UserSicknesses

    public partial class UserSicknesses
{
    public int SicknessId { get; set; }
    public string UserId { get; set; }
    public System.DateTime StartDate { get; set; }
    public System.DateTime EndDate { get; set; }

    public AspNetUsers AspNetUsers { get; set; }
}

In my View I want to submit the Username of the AspNetUsers and the two dates from UserSicknesses

    <div class="form-group row">
    @Html.LabelFor(model => model.AspNetUsers.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-xs-10">
        @Html.EditorFor(model => model.AspNetUsers.UserName, new { htmlAttributes = new { @class = "form-control"} })
        @Html.ValidationMessageFor(model => model.AspNetUsers.UserName, "", new { @class = "text-danger" })
    </div>
</div>
<div class="form-group row">
    @Html.LabelFor(model => model.StartDate, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-xs-10">
        @Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { @class = "form-control", type = "date" } })
        @Html.ValidationMessageFor(model => model.StartDate, "", new { @class = "text-danger" })
    </div>
</div>
<div class="form-group row">
    @Html.LabelFor(model => model.EndDate, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-xs-10">
        @Html.EditorFor(model => model.EndDate, new { htmlAttributes = new { @class = "form-control", type = "date" } })
        @Html.ValidationMessageFor(model => model.EndDate, "", new { @class = "text-danger" })
    </div>
</div>

The problem now is that userSicknesses.AspNetUsers is Null when posting and I can't receive UserName. They are both connected by the UserId, but I just want to get the UserName and the two dates.

        [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "SicknessId,StartDate,EndDate,UserName")] UserSicknesses userSicknesses)
    {

        if (ModelState.IsValid && User.Identity.IsAuthenticated)
        {
            if (userSicknesses.StartDate > userSicknesses.EndDate)
            {
                ModelState.AddModelError("StartDate", "Das erste Datum kann nicht größer als das zweite sein!");
                return View(userSicknesses);
            }
            int sicId = 1;

            // Just for testing purposes but userSicknesses.AspNetUsers is Null
            string s = userSicknesses.AspNetUsers.UserName;

            if (db.UserSicknesses.Any())
            {
                sicId = (from a in db.UserSicknesses select a.SicknessId).Max() + 1;
            }
            userSicknesses.SicknessId = sicId;

            userSicknesses.UserId = db.AspNetUsers.Where(u => u.UserName == userSicknesses.AspNetUsers.UserName).Select(u => u).FirstOrDefault().ToString();

            db.UserSicknesses.Add(userSicknesses);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(userSicknesses);
    }

In the Form Data Firefox tells me: __RequestVerificationToken:KlY6b4CD41PaGoKJ... AspNetUsers.UserName:admin StartDate:2016-12-04 EndDate:2016-12-18

What am I doing wrong? Thank you in advance.

btw: this is my first project in asp.net and I appreciate every advice!

tereško
  • 58,060
  • 25
  • 98
  • 150
niknot
  • 43
  • 5
  • One relatively easy way is to create yourself a different model for this purpose. This model should contain all the fields you need to process your request. – bash.d Dec 07 '16 at 13:17
  • That would be one option. But I find that kind of dirty? I mean my "UserSicknesses " model has its AspNetUsers variable so why am I not able to fill it? – niknot Dec 07 '16 at 13:36

2 Answers2

1

Check below code for pass this result:

$('#btnClick').on('click', function () {
var UserSicknesses= {
                    "AspNetUsers.UserName": $("#AspNetUsers_UserName").val(),
                    "StartDate ": $("#StartDate").html(),
                    "EndDate": $("#EndDate").val()

                };

                $.ajax({
                    url: '/ControllerName/Create',
                    type: "Post",
                    async: false,
                    data: JSON.stringify(UserSicknesses),
                    dataType: "html",
                    contentType: "application/json;charset=utf-8",
                    success: function (result) {
                        $("#gdiv").empty();
                        $("#gdiv").html(result);

                    }
                });
  });
Laxman Gite
  • 2,248
  • 2
  • 15
  • 23
  • change your action like this and chek : public ActionResult Create(UserSicknesses userSicknesses) – Laxman Gite Dec 07 '16 at 13:41
  • 1
    Wow now it works! Thank you very much! But I wonder why that "[Bind(Include = "SicknessId,UserId,StartDate,EndDate")]" needed to be removed.. – niknot Dec 07 '16 at 13:57
0

I think you can use a ViewModel that contains both models and pass it to the view. check this answer, it's very similar to your problem

Community
  • 1
  • 1
Orion_Dev
  • 29
  • 4