当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net mvc - Show a message from ViewBag set in a controller on an Exception and Stay in the same View

问题描述:

What I have

A single view 'AddEdit.cshtml' that is used to both Edit and also Delete a Student entity.

Edit ActionResult:

public ActionResult Edit(int Id)

{

// code to get the Student object create a VM and call the view passing the VM

ViewBag.Mode = "Edit";

return View("AddEdit", studentVm);

}

Delete button in the same view:

@Html.ActionLink("Delete Student", "Delete", new { id = Model.StudentId }, new { role = "button", @class = "btn btn-danger",id="deleteStudent" })

In case of an exception when deleting I want to inform the user by showing a message in a alert so I added this code:

public ActionResult Delete(int id)

{

var student = _publisherManager.GetStudentById(id);

try

{

_studentManager.DeleteStudent(student);

}

catch (Exception ex) {

// Logging code

ViewBag.DeleteStudentError = "This student is currently acitve and cannot be deleted.";

// Code to get the VM same as in the Edit method and call the view with it

return View("AddEdit", studentVm);

}

// All well go to the Index view

return RedirectToAction("Index");

}

Not able to do

  1. Show the message from ViewBag

  2. The Url after the click says

Student/Delete/14

Instead of

Student/Edit?Id=14

Any clues?

Thanks in advance.

网友答案:

Your url will be always Student/Delete/14. If you want to change this to Edit you must redirect your action.

That is,

public ActionResult Delete(int id) 
{
    var student = _publisherManager.GetStudentById(id);
    try
    {
        _studentManager.DeleteStudent(student);
    }
    catch (Exception ex) {
        // Logging code
        // You can't use ViewBag because we will redirect to another action.
        //ViewBag.DeleteStudentError = "This student is currently acitve and cannot be deleted.";

        // You can use TempData to pass parameter across actions
        TempData["DeleteStudentError"] = "This student is currently acitve and cannot be deleted.";


        // Code to get the VM same as in the Edit method and call the view with it
        return RedirectToAction("Action_Name_Of_Edit",student);

    }
    // All well go to the Index view
    return RedirectToAction("Index");
}

And you can use this TempData["DeleteStudentError"] in your AddEdit.cshtml.

Your view should be,

<span class="alert"> @(TempData["DeleteStudentError"]??string.Empty) <span>
分享给朋友:
您可能感兴趣的文章:
随机阅读: