public ActionResult MyActionMethod(MyModel model)
{
//some code
string myVar= ActionMethod2(model).toString();
//use myVar
Method3(myVar, otherVar);
}
public ActionResult ActionMethod2()(MyModel model)
{
return View(model);
}
private Method3(string myVar, int otherVar)
{
//do something;
}
作为上面的示例代码,我有一个返回.cshtml
视图的方法,名为ActionMethod2
。
我想在我的action方法中使用返回的html作为字符串变量。怎么可能?
答案 0 :(得分:1)
您可以使用Content Method
。
public ActionResult ActionMethod2()
{
return Content("YourHTMLString");
}
或者您可以将返回类型设置为字符串并传递 HTML字符串。
public string ActionMethod2()
{
return "<html></html>";
}
答案 1 :(得分:0)
第一个错误是ActionMethod2
返回查看,您可以直接从MyActionMethod
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (var sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
public ActionResult MyActionMethod(MyModel model)
{
//some code
//string myVar= ActionMethod2(model).toString();
var myVar = RenderPartialViewToString("yourviewName", model);
//use myVar
Method3(myVar, otherVar);
}
尝试这个,它将与你合作。
答案 2 :(得分:0)
方法一个可以传递你想要的参数作为RedirectToAction()方法的routeValues参数的一部分。使用传递的查询字符串数据。
或者你可以借助查询字符串来构建它,例如:
return RedirectToAction( "Main", new RouteValueDictionary(
new { controller = controllerName, action = "YourActionName", Id = Id}) );
或者您可以使用TempData:
[HttpPost]
public ActionResult MyActionMethod(MyModel model)
{
TempData["myModal"]= new MyModel();
return RedirectToAction("ActionMethod2");
}
[HttpGet]
public ActionResult ActionMethod2()
{
MyModel myModal=(MyModel)TempData["myModal"];
return View();
}
在浏览器的URL栏中 此解决方案使用临时cookie:
[HttpPost]
public ActionResult Settings(SettingsViewModel view)
{
if (ModelState.IsValid)
{
//save
Response.SetCookie(new HttpCookie("SettingsSaveSuccess", ""));
return RedirectToAction("Settings");
}
else
{
return View(view);
}
}
[HttpGet]
public ActionResult Settings()
{
var view = new SettingsViewModel();
//fetch from db and do your mapping
bool saveSuccess = false;
if (Request.Cookies["SettingsSaveSuccess"] != null)
{
Response.SetCookie(new HttpCookie("SettingsSaveSuccess", "") { Expires = DateTime.Now.AddDays(-1) });
saveSuccess = true;
}
view.SaveSuccess = saveSuccess;
return View(view);
}
或尝试方法4: 只需调用操作,无需重定向到操作,也无需调用new关键字进行模型。
[HttpPost]
public ActionResult MyActionMethod(MyModel myModel1)
{
return ActionMethod2(myModel1); //this will also work
}
public ActionResult ActionMethod2(MyModel myModel)
{
return View(myModel);
}