LINQ To Entities SaveChanges () не работает - PullRequest
0 голосов
/ 26 августа 2018

У меня есть сценарий, в котором у меня есть форма, в которой я хотел бы, чтобы администраторы изменили свои данные экзамена / опроса. Я пытаюсь обновить свою таблицу базы данных следующим кодом.

Однако код не сохраняет мои изменения для части «если» в моем контроллере, и не выдает никакой ошибки, а просто перенаправляет меня на следующую страницу «EditExam2».

Я пытаюсь обновить поля «InformationSheetText» и «InformationConsentForm».

Я знаю, что запрос работает так же, как часть «else» моего кода в моем контроллере, когда добавляется новая строка в базу данных.

My View

@model  
 AppXamApplication.Models
InformationSheetViewModel
@{
    ViewBag.Title = "InformationSheet";
}
<!DOCTYPE html>
<html>
<body>
<h2>InformationSheet</h2>
<h3>Survey ID: @ViewBag.CurrentExamID</h3>

@using (Html.BeginForm("InformationSheet", "ExamAdmin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <h4>Create Information and Consent Sheet.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })

    <div class="form-group">
        @Html.LabelFor(m => m.ImageURL, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            <input type="file" name="ImageFile" />
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.InformationSheetText, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.EditorFor(m => m.InformationSheetText, new { @class = "form-control", @rows = 4, @style = "resize: none;" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-10">
            @Html.CheckBoxFor(m => m.Check_InformationSheet, new { @disabled = "disabled", @checked = true })
            @Html.LabelFor(m => m.Check_InformationSheet, new { })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.InformationConsentForm, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.EditorFor(m => m.InformationConsentForm, new { @class = "form-control", @rows = 4, @style = "resize: none;" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-10">
            @Html.CheckBoxFor(m => m.Check_InformationConsentForm1, new { @disabled = "disabled", @checked = true })
            @Html.LabelFor(m => m.Check_InformationConsentForm1, new { })
        </div>

        <div class="col-md-10">
            @Html.CheckBoxFor(m => m.Check_InformationConsentForm2, new { @disabled = "disabled", @checked = true })
            @Html.LabelFor(m => m.Check_InformationConsentForm2, new { })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Create Exam" />
        </div>
    </div>
}
 @section Scripts {
 @Scripts.Render("~/bundles/jqueryval")
}

Моя модель

public class InformationSheetViewModel
{
    public string ExamID { get; set; }

    [Display(Name = "Choose Image To Display")]
    public string ImageURL { get; set; }

    [Display(Name = "Enter your Information Sheet")]
    public string InformationSheetText { get; set; }

    [Display(Name = "Enter your Consent Form")]
    public string InformationConsentForm { get; set; }

    public HttpPostedFileBase ImageFile { get; set; }

    [Display(Name = "I had read and understood the information sheet")]
    public bool Check_InformationSheet { get; set; }

    [Display(Name = "I consent and agree to the information consent form")]
    public bool Check_InformationConsentForm1 { get; set; }

    [Display(Name = "I have read, agree and consent to the information and conditions")]
    public bool Check_InformationConsentForm2 { get; set; }

}

Мой контроллер

[HttpGet]
public ActionResult InformationSheet(string id)
{
    if (ModelState.IsValid)
    {
        ViewBag.CurrentExamID = id;
        using (var ctx = new AppXamApplicationEntities())
        {
            var query = ctx.InformationConsentAndSheets.Where(x => x.ExamID.Equals(id)).Select(x => new InformationSheetViewModel()
            {
               ExamID = id,
               InformationSheetText = x.InformationSheetText,
               InformationConsentForm = x.InformationSheetText
           }).FirstOrDefault();
           return View(query);                    
        }
    }
     return View();
}


[HttpPost]
[Authorize(Roles = "ExamAdmin")]
[ValidateAntiForgeryToken]
public ActionResult InformationSheet(string id, InformationSheetViewModel model)
{
    using (var ctx = new AppXamApplicationEntities())
    {
       InformationConsentAndSheet query = ctx.InformationConsentAndSheets.Where(x => x.ExamID.Equals(id)).FirstOrDefault();
       if (query != null)
       {   
           //To insert picture into database as well as folder
           string fileName = Path.GetFileNameWithoutExtension(model.ImageFile.FileName);
           string extension = Path.GetExtension(model.ImageFile.FileName);
           fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
           model.ImageURL = "~/Image/" + fileName;
           fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
           model.ImageFile.SaveAs(fileName);

           query = new InformationConsentAndSheet()
           { 
              ExamID = id,
              ImageURL = model.ImageURL,
              InformationSheetText = model.InformationSheetText,
              InformationConsentForm = model.InformationConsentForm
           };
           ctx.SaveChanges();
       }
       else
       {
            //To insert picture into database as well as folder
            string fileName = Path.GetFileNameWithoutExtension(model.ImageFile.FileName);
            string extension = Path.GetExtension(model.ImageFile.FileName);
            fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
            model.ImageURL = "~/Image/" + fileName;
            fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
            model.ImageFile.SaveAs(fileName);

            query = new InformationConsentAndSheet()
            {
               ExamID = id,
               ImageURL = model.ImageURL,
               InformationConsentForm = model.InformationConsentForm,
               InformationSheetText = model.InformationSheetText
            };
            ctx.InformationConsentAndSheets.Add(query);
            ctx.SaveChanges();
        }
    return RedirectToAction("EditExam2");
}

}

Я очень озадачен тем, что не так с моим кодом, любая помощь будет очень признательна, так как я чрезвычайно новичок в MVC в целом.

1 Ответ

0 голосов
/ 28 августа 2018

Прежде всего, вам нужно отправить свой идентификатор опроса, когда вы хотите редактировать.Это можно легко сделать с помощью параметров маршрута в вашей форме.

@using (Html.BeginForm("InformationSheet", "ExamAdmin", new { id = ViewBag.CurrentExamID }, FormMethod.Post, new { enctype = "multipart/form-data" }))

Ваш код для редактирования существующего элемента немного неправильный.Вам необходимо изменить существующий InformationConsentAndSheet, а не создавать новый.

       InformationConsentAndSheet query = ctx.InformationConsentAndSheets.Where(x => x.ExamID.Equals(id)).FirstOrDefault();
       if (query != null)
       {   
          // work with files

           query.ExamID = id;
           query.ImageURL = model.ImageURL;
           query.InformationSheetText = model.InformationSheetText;
           query.InformationConsentForm = model.InformationConsentForm;

           ctx.Entry(query).State = EntityState.Modified;
           ctx.SaveChanges();
       }

Перед отправкой изменений необходимо указать, что запрос был отредактирован и должен быть сохранен.

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...