asp.net-mvc 我们可以在 RedirectToAction 中将模型作为参数传递吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22505674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:36:23  来源:igfitidea点击:

Can we pass model as a parameter in RedirectToAction?

asp.net-mvcasp.net-mvc-3asp.net-mvc-4controller

提问by Amit

I want to know, there is any technique so we can pass Modelas a parameter in RedirectToAction

我想知道,有什么技术可以让我们Model作为参数传入RedirectToAction

For Example:

例如:

public class Student{
    public int Id{get;set;}
    public string Name{get;set;}
}

Controller

控制器

public class StudentController : Controller
{
    public ActionResult FillStudent()
    {
        return View();
    }
    [HttpPost]
    public ActionResult FillStudent(Student student1)
    {
        return RedirectToAction("GetStudent","Student",new{student=student1});
    }
    public ActionResult GetStudent(Student student)
    {
        return View();
    }
}

My Question - Can I pass student model in RedirectToAction?

我的问题 - 我可以在 RedirectToAction 中传递学生模型吗?

回答by Murali Murugesan

Using TempData

使用临时数据

Represents a set of data that persists only from one request to the next

表示仅从一个请求持续到下一个请求的一组数据

[HttpPost]
public ActionResult FillStudent(Student student1)
{
    TempData["student"]= new Student();
    return RedirectToAction("GetStudent","Student");
}

[HttpGet]
public ActionResult GetStudent(Student passedStd)
{
    Student std=(Student)TempData["student"];
    return View();
}

Alternative wayPass the data using Query string

替代方式使用查询字符串传递数据

return RedirectToAction("GetStudent","Student", new {Name="John", Class="clsz"});

This will generate a GET Request like Student/GetStudent?Name=John & Class=clsz

这将生成一个 GET 请求,如 Student/GetStudent?Name=John & Class=clsz

Ensure the method you want to redirect to is decorated with [HttpGet]as the above RedirectToAction will issue GET Request with http status code 302 Found (common way of performing url redirect)

确保您要重定向到的方法被装饰,[HttpGet]因为上面的 RedirectToAction 将发出带有 http 状态代码 302 Found 的 GET 请求(执行 url 重定向的常用方法)

回答by Vinay Pratap Singh

Just call the action no need for redirect to actionor the newkeyword for model.

只需调用不需要的操作redirect to actionnew模型的关键字。

 [HttpPost]
    public ActionResult FillStudent(Student student1)
    {
        return GetStudent(student1); //this will also work
    }
    public ActionResult GetStudent(Student student)
    {
        return View(student);
    }

回答by Vinay Pratap Singh

Yes you can pass the model that you have shown using

是的,您可以使用已显示的模型传递

return RedirectToAction("GetStudent", "Student", student1 );

assuming student1is an instance of Student

假设student1是一个实例Student

which will generate the following url (assuming your using the default routes and the value of student1are ID=4and Name="Amit")

这将生成以下网址(假设您使用默认路由和student1are ID=4and的值Name="Amit"

.../Student/GetStudent/4?Name=Amit

.../Student/GetStudent/4?Name=Amit

Internally the RedirectToAction()method builds a RouteValueDictionaryby using the .ToString()value of each property in the model. However, binding will only work if all the properties in the model are simple properties and it fails if any properties are complex objects or collections because the method does not use recursion. If for example, Studentcontained a property List<string> Subjects, then that property would result in a query string value of

在内部,该RedirectToAction()方法RouteValueDictionary通过使用.ToString()模型中每个属性的值来构建一个。但是,绑定仅在模型中的所有属性都是简单属性时才有效,如果任何属性是复杂对象或集合,绑定就会失败,因为该方法不使用递归。例如,如果Student包含一个属性List<string> Subjects,则该属性将导致查询字符串值为

....&Subjects=System.Collections.Generic.List'1[System.String]

....&Subjects=System.Collections.Generic.List'1[System.String]

and binding would fail and that property would be null

并且绑定将失败并且该属性将是 null

回答by hansen.palle

  [HttpPost]
    public async Task<ActionResult> Capture(string imageData)
    {                      
        if (imageData.Length > 0)
        {
            var imageBytes = Convert.FromBase64String(imageData);
            using (var stream = new MemoryStream(imageBytes))
            {
                var result = (JsonResult)await IdentifyFace(stream);
                var serializer = new JavaScriptSerializer();
                var faceRecon = serializer.Deserialize<FaceIdentity>(serializer.Serialize(result.Data));

                if (faceRecon.Success) return RedirectToAction("Index", "Auth", new { param = serializer.Serialize(result.Data) });

            }
        }

        return Json(new { success = false, responseText = "Der opstod en fejl - Intet billede, manglede data." }, JsonRequestBehavior.AllowGet);

    }


// GET: Auth
    [HttpGet]
    public ActionResult Index(string param)
    {
        var serializer = new JavaScriptSerializer();
        var faceRecon = serializer.Deserialize<FaceIdentity>(param);


        return View(faceRecon);
    }

回答by Er. Binod Mehta

[NonAction]
private ActionResult CRUD(someModel entity)
{
        try
        {
            //you business logic here
     return View(entity);
       }                                
         catch (Exception exp)
         {
             ModelState.AddModelError("", exp.InnerException.Message);
             Response.StatusCode = 350;
             return someerrohandilingactionresult(entity, actionType);
         }
         //Retrun appropriate message or redirect to proper action
      return RedirectToAction("Index");   
}

回答by DiSaSteR

i did find something like this, helps get rid of hardcoded tempdata tags

我确实找到了这样的东西,有助于摆脱硬编码的临时数据标签

public class AccountController : Controller
{
    [HttpGet]
    public ActionResult Index(IndexPresentationModel model)
    {
        return View(model);
    }

    [HttpPost]
    public ActionResult Save(SaveUpdateModel model)
    {
        // save the information

        var presentationModel = new IndexPresentationModel();

        presentationModel.Message = model.Message;

        return this.RedirectToAction(c => c.Index(presentationModel));
    }
}