【问题标题】:asp.net return same view but delete url?asp.net 返回相同的视图但删除 url?
【发布时间】:2015-08-27 10:43:33
【问题描述】:

我有一个项目,我在其中报告不同项目的时间,我正在努力,所以我可以删除报告,以防我做错了,这工作得体。 当我转到所有报告的摘要页面时,它会列出所有日期,我单击日期并将其发送到 TimeReport 视图,如下所示:

http://localhost:9061/Reports/TimeReport/b604a74a-2034-4916-9534-57788db1e8e2

然后它会检查 ReportId 是否有这样的值:

                                @if (Model.ReportId.HasValue)
                            {
                                <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#basic">Ta bort!</button>
                            }

如果它存在,将出现一个删除按钮,我单击删除按钮,它将删除报告。但是 URL 仍然相同,因此如果我刷新站点,我的应用程序将崩溃,因为该 ID 不再存在于数据库中。

            if (form != null && form.AllKeys.Contains("delete"))
        {
            new DatabaseLayer().DeleteTimeReport(Guid.Parse(form["ReportId"]));
            LoadDefaultSettings(projectData);
            ViewData.Model = projectData;
            ViewData["deleted"] = true;
            return View();
        }

这是检查 GUID 是否存在的模型。

public void SaveToDatabase(Guid consultantId)
        {
            using (DatabaseLayer db = new DatabaseLayer())
            {
                //Time report exists, delete it.
                if (ReportId.HasValue)
                {
                    db.DeleteTimeReport(ReportId.Value);
                }
                //Time report does not exist, create a new one.
                else
                {
                    ReportId = Guid.NewGuid();
                }


                Report report = new Report
                {
                    FK_ConsultantID = consultantId,
                    FK_UserID = Constants.UserTreetop,
                    Date = Date,
                    TimeReportID = ReportId.Value
                };

                TimeReportData reportData = new TimeReportData
                {
                    Absent = 0,
                    Description = "",
                    StartHour = Times.StartHour,
                    StartMinute = Times.StartMinute,
                    EndHour = Times.EndHour,
                    EndMinute = Times.EndMinute,
                    BreakHour = Times.BreakHour,
                    BreakMinute = Times.BreakMinute,
                    FK_TimeReportID = ReportId.Value,
                    TimeReportDataID = Guid.NewGuid()
                };

                TimeReportProject[] reportProjects = new TimeReportProject[Projects.Count];
                for (int i = 0; i < Projects.Count; i++)
                {
                    reportProjects[i] = new TimeReportProject
                    {
                        Description = Projects[i].Description,
                        FK_ProjectID = Projects[i].ProjectId,
                        FK_TimeReportID = ReportId.Value,
                        Hours = Projects[i].Hours.GetValueOrDefault(), //Projects[i].Hours.Value,
                        HourRate = db.GetProjectHourRate(Projects[i].ProjectId, Date, Projects[i].Hours.GetValueOrDefault()),
                        TimeReportProjectID = Guid.NewGuid()
                    };
                }

                db.InsertTimeReport(report, reportData, reportProjects);
            }
        }

因为它存在,所以它会这样做

        public void DeleteTimeReport(Guid timeReportId)
    {

        db.ExecuteStoreCommand(
            @"  DELETE FROM [Salesweb].[dbo].[TimeReportProject] WHERE FK_TimeReportID = @id;
                DELETE FROM [Salesweb].[dbo].[TimeReportData] WHERE FK_TimeReportID = @id;
                DELETE FROM [Salesweb].[dbo].[TimeReport] WHERE TimeReportID = @id;"
            , new SqlParameter("@id", timeReportId));

        db.SaveChanges();
    }

这是当我传入要删除的 guid 时的视图,因为 guid 有一个值,删除按钮将出现。

但当我删除项目时,它会返回相同的视图。就像我们可以看到选项卡没有显示一样,所以如果我想再次显示,我必须转到另一个视图,而不是返回相同的视图。如果我刷新它会崩溃,因为数据库中不存在 guid。

这是整个控制器,现在有点乱。

public ActionResult TimeReport(FormCollection form, Guid? id)
    {
        ViewDataDictionary vd = new ViewDataDictionary
        {
            ["projects"] = new DatabaseLayer().GetConsultantProjects(Constants.CurrentUser(User.Identity.Name)),
            ["id"] = 1,
            ["showDescription"] = true
        };
        ViewData["vd"] = vd;

        NewTimeReportModel projectData = new NewTimeReportModel();

        if (form != null && form.AllKeys.Contains("delete"))
        {
            new DatabaseLayer().DeleteTimeReport(Guid.Parse(form["ReportId"]));
            LoadDefaultSettings(projectData);
            ViewData.Model = projectData;
            ViewData["deleted"] = true;
            return RedirectToAction("Index");
        }

        if (id.HasValue && (form == null || form.AllKeys.Length == 0))
        {
            using (DatabaseLayer db = new DatabaseLayer())
            {
                var timeReport = db.GetTimeReport(id.Value);
                projectData = new NewTimeReportModel(timeReport);
                if (projectData.Projects.Count == 1)
                    projectData.Projects[0].Hours = null;
            }
        }
        else if (form == null || form.AllKeys.Length == 0)
        {
            LoadDefaultSettings(projectData);
        }
        else
        {
            //Get's all the dates from the view and formates them to look like yy-mm-dd so we can parse it to a datetime.
            string[] dates = FormateDate(form["date"]);
            //Loops over all the dates and saves the dates to the database.
            projectData = ReportDates(form, projectData, dates);
            //Loads default settings if all dates been reported.
            LoadDefaultSettings(projectData);
        }
        //Get's and lists all the missing days
        ListAllMssingDays();
        ViewData.Model = projectData;
        return View();
    }

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    在这种情况下,建议执行重定向到某个默认 URL,例如摘要页面。猜测你有 Summary 动作,应该是这样的:

    if (form != null && form.AllKeys.Contains("delete"))
    {
        new DatabaseLayer().DeleteTimeReport(Guid.Parse(form["ReportId"]));
        return RedirectToAction("Summary", "Reports");
    }
    

    请注意,这将执行客户端重定向,也就是说 - 这将使用代码 302 和新 URL /Reports/Summary 进行响应。不过,这通常是一种理想的行为。

    【讨论】:

    • 这仍然使它重新加载正在发送的 ID,并且由于 ID 不再存在,应用程序崩溃。
    • @JoakimCarlsson,但是为什么要重新加载带有已删除 ID 的同一页面?
    • @JoakimCarlsson,无论如何,你可以做SingleOrDefault,如果结果为空,做同样的重定向
    【解决方案2】:

    您得到的例外是因为您的代码假定您要删除的项目将存在。

    改变

    return db.TimeReports.Where(x => x.TimeReportID == timeReportId).Single();
    

    到

    return db.TimeReports.Where(x => x.TimeReportID == timeReportId).SingleOrDefault();
    

    如果您的 Where 子句返回 0 项,则返回 null。

    然后,无论您在代码中调用GetTimeReport() 的哪个位置,都需要检查并处理空值。

    【讨论】:

    • 它可以工作,但 URL 仍然使用 GUID,只要我的 GUID 在 url 中,它就不会加载我没有报告时间的日期,所以我必须去另一个视图,而不是回到同一个视图来查看那些日期。或手动编辑 URL。
    • 你能包含整个控制器动作吗?
    • 对不起,我的意思是您的删除请求的控制器操作以及正常请求的控制器操作。
    • 完成了,很抱歉我的互联网延迟了几个小时。
    猜你喜欢
    • 2010-10-06
    • 1970-01-01
    • 2019-06-04
    • 2015-07-20
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    相关资源
    最近更新 更多