Passing action and controller values from view to another partialview - c#

I have multiple index views with a different grid in each of these views, but all of them uses the same popup control. I dont want to make a partial view foreach index view that i have. So i put the popup partial view in the Shared folder.
But i have a Html.BeginForm('Action','Controller') in the popup partialview, and these values are different in each grid. How can i pass these from the view of the grid to the partial view of the popup?
The Grid View:
//Code Resumed
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "TestMasterGrid";
settings.Column.Add("Id");
settings.Column.Add("Name");
settings.Column.Add("Email");
//Command Column Wich calls the popup control
}
The PopUp PartialView:
//Code resumed
using (Html.BeginForm("ActionINeedToGetFromTheGridView", "ControllerINeedToGetFromTheGridView", FormMethod.Post))
{
Html.DevExpress().TextBox(
textBoxSettings =>
{
textBoxSettings.Name = "reason";
textBoxSettings.ControlStyle.CssClass = "editor";
})
.Render();
Html.DevExpress().Label(
labelSettings =>
{
labelSettings.Name = "sh";
labelSettings.ControlStyle.CssClass = "label";
}).Render();
Html.DevExpress().Button(
buttonSettings =>
{
buttonSettings.Name = "btnUpdate";
buttonSettings.ControlStyle.CssClass = "button";
buttonSettings.Width = 80;
buttonSettings.Text = "OK";
buttonSettings.UseSubmitBehavior = true;
}
)
.Render();
Thanks!

Pass the action and controller names to the action that returns the PartialViewResult. Then, pass the names to the partial's model and use them in the BeginForm statement:
Html.BeginForm(Model.Action, Model.Controller, FormMethod.Post)
Edit:
I'm not very familiar with DevExpress, but I found the CallbackRouteValues member in settings. I'll use that for my example:
settings.CallbackRouteValues = new { Controller = "ControllerName", Action = "GetPartialView", desiredAction = "DesiredAction", desiredController = "DesiredController" }
In your controller, you'd have the action and controller parameters:
public PartialViewResult GetParialView(string desiredAction, string desiredController) {
var viewModel = new PartialViewModel { Action = desiredAction, Controller = desiredController);
Return PartialView("Name", viewModel);
}
I typed out this code by hand, so it's probably full of errors. Hopefully it gets the idea across, though.
Quick edit: changed some parameter names to make it a little clearer.

Related

MVC Pass value/parameter from controller to View

what i'm trying to achieve:
1. fill up form
2. save into database
3. redirect user to another view that displays some details (referenceID)
so here's what i have
controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ClearanceViewModel myViewModel, TClearance clearance, TRefsNum referenceNo)
{
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var stringChars = new char[8];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
string refNo = DateTime.Now.Year + finalString;
items.RefNum = refNo;
db.TClearances.Add(items);
db.SaveChanges();
return RedirectToAction(items.RefNum, "displayRef");
}
code above does save to database whatever user has input then redirect to view "displayRef" and items.refNum is the value that i'm trying to pass to view
view:
#model RDMSPNPOnlineClearance.Models.TClearance
#{
var getRef = Model.RefNum;
}
this is your ref number: #Html.LabelFor(model => model.RefNum, htmlAttributes: new { #class = "control-label" })
code above, is trying to get the expected value "items.refNum" and use the value to display it to the user.
so what actually happening is, user fill ups, saves to db, then redirected to "displayRef" view. no problem in saving part. the problem is im not getting the refNum in the displayRef view. the url changes to something like:
Localhost:55433/items.refNum/view
so, how do i pass that value to be displayed to the user?
Do you need RedirectToAction? Can you not just return the view...
return View("displayRef", items.RefNum);
If you have to use RedirectToAction, this means you're redirecting to a controller action and you must specify it like so...
return RedirectToAction("Action","controller", new {#id=id});
Also your model in the view is incorrect, you're binding a string refNo, but at the top of your view stating that you want to bind a class RDMSPNPOnlineClearance.Models.TClearance

MVC, Data in controller from model in model

i have some problems with my input data in asp.net mvc on controller site. My model include another model which is binded on some textboxs.
My main model Order include a model Customer (with a string property of first name).
Example main page (i use dev express controls), i give the model to the group:
#model Models.Order
#using (Html.BeginForm("Index", "Main"))
{
<div>
#Html.DevExpress().NavBar(settings =>
{
settings.Name = "nbWebshopSteps";
settings.EnableClientSideAPI = true;
settings.Width = new Unit(100, UnitType.Percentage);
settings.Groups.Add(group =>
{
group.Text = "Bestellung bestätigen";
group.Expanded = false;
group.ShowExpandButton = DefaultBoolean.False;
group.ContentStyle.Border.BorderColor = Color.FromArgb(247, 242, 212);
group.SetHeaderTemplateCollapsedContent(c => Html.RenderPartial("../Main/NavBarHeaderCollapsed", c.Group));
group.SetHeaderTemplateContent(c => Html.RenderPartial("NavBarHeader", c.Group));
group.SetContentTemplateContent(c => Html.RenderPartial("PersonalData", Model));
});
}).GetHtml()
}
My personal data pagem, which is rendered into the group (it comes from a dll):
#model Objects.Customer <div>
#Html.DevExpress().TextBox(settings =>
{
settings.Name = "txtFirstName";
settings.Properties.Caption = "Vorname";
settings.EncodeHtml = false;
settings.Properties.CaptionStyle.Font.Size = 14;
settings.Width = 385;}).Bind(Model.Firstname).GetHtml()</div>
After the postback my customer model is empty (first name).
[HttpPost]
public ActionResult Index(Order order)
{
}
Can someone help me?
Thanks
Take a look at this article.
DevExpress support recommend to use code like this:
#Html.DevExpress().TextBox(settings => {
//settings.Name = "Street";
settings.Name = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName("Street");
}).Bind(Model.Street).GetHtml()

How to retain parameters for xtraReport with a dataset as the datasource

I have a devExpress xtraReport that is being supplied by a strongly typed dataset. As long as I'm hard coding two parameters into the Actions, it loads the data into the dataset and displays in the report. Once I try to make it pass the values from the main page down through the partial, it fails. My first attempt was to pass the parameters through the ViewBag, wasn't working, so switched to a model, still not working right.
main page controller
public ActionResult SubsequentVisitReport(int noteType = 1, int noteId = 9)
{
ViewBag.noteType = noteType;
ViewBag.noteId = noteId;
ReportParameters reportParamters = new ReportParameters();
reportParamters.noteType = noteType;
reportParamters.noteId = noteId;
return View(reportParamters);
}
main page cshtml - added in the EditorFor to make sure the model makes it there (it does). Have tried calling the Partial both with and without putting 'Model'
#model ReportParameters
#Html.EditorFor(m => m.noteId)
#Html.EditorFor(m => m.noteType)
#Html.HiddenFor(m => m.id)
#Html.HiddenFor(m => m.noteType)
#Html.HiddenFor(m => m.noteId)
#Html.Partial("_SubsequentVisitReport", Model)
controller for the partial - this does not receive the data from the model and I don't understand why. The model is NOT null, all the values are 0 (zero).
[HttpPost]
public ActionResult _SubsequentVisitReport(ReportParameters model)
{
int noteType = model.noteType;
int noteId = model.noteId;
rptSubsequentVisit report = new rptSubsequentVisit();
try { report.DataSource = getSubsequentVisitData(model.noteType, model.noteId).Tables[0]; }
catch { return RedirectToAction("Not_Authorized"); }
ViewData["Report"] = report;
return PartialView("_SubsequentVisitReport");
}
The view for the partial
#model ReportParameters
#Html.HiddenFor(m => m.id)
#Html.HiddenFor(m => m.noteType)
#Html.HiddenFor(m => m.noteId)
#Html.DevExpress().DocumentViewer(settings =>
{
// The following settings are required for a Report Viewer.
settings.Name = "reportViewer1";
settings.Report = (rptSubsequentVisit)ViewData["Report"];
// Callback and export route values specify corresponding controllers and their actions.
// These settings are required as well.
settings.CallbackRouteValues = new { Controller = "Reports", Action = "_SubsequentVisitReport"};
settings.ExportRouteValues = new { Controller = "Reports", Action = "_SubsequentVisitReportExport" };
}).GetHtml()
The data needs to persist through the partial both to load the note for viewing, but also for the export function.
What am I doing wrong, or is there another better way to do this?
Thanks,
Dave K.
The settings.CallbackRouteValues object tells the DocumentViewer where to request the actual report, and it can take parameters. Unfortunately it will be a separate request, so you can't send your model, only simple values that can be passed as strings. In this example, they are using a custom model for the report, but the model has to be re-created from raw values in each action.
If you convert your partial action to take integer parameters:
public ActionResult _SubsequentVisitReport(int noteType, int noteId)
you should be able to tack those arguments on the end of the CallbackRouteValues:
settings.CallbackRouteValues = new { Controller = "Reports",
Action = "_SubsequentVisitReport",
noteType = model.noteType,
noteId = model.noteId};

Redirecting from cshtml page

I want to redirect to a different view depending on the result of a dataset, but I keep getting returned to the page I am currently on, and can't work out why. I drop into the if statement the action gets called but once i return the view to the new page, it returns me back to the current page.
CSHTML page
#{
ViewBag.Title = "Search Results";
EnumerableRowCollection<DataRow> custs = ViewBag.Customers;
bool anyRows = custs.Any();
if(anyRows == false)
{
Html.Action("NoResults","Home");
}
// redirect to no search results view
}
Controller
public ActionResult NoResults()
{
return View("NoResults");
}
View I cant get too..
#{
ViewBag.Title = "NoResults";
}
<h2>NoResults</h2>
Change to this:
#{ Response.Redirect("~/HOME/NoResults");}
Would be safer to do this.
#{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}
So the controller for that action runs as well, to populate any model the view needs.
Source
Redirect from a view to another view
Although as #Satpal mentioned, I do recommend you do the redirecting on your controller.
This clearly is a bad case of controller logic in a view. It would be better to do this in a controller and return the desired view.
[ChildActionOnly]
public ActionResult Results()
{
EnumerableRowCollection<DataRow> custs = ViewBag.Customers;
bool anyRows = custs.Any();
if(anyRows == false)
{
return View("NoResults");
}
else
{
return View("OtherView");
}
}
Modify NoResults.cshtml to a Partial.
And call this as a Partial view in the parent view
#Html.Partial("Results")
You might have to pass the Customer collection as a model to the Result action or in a ViewDataDictionary due to reasons explained here: Can't access ViewBag in a partial view in ASP.NET MVC3
The ChildActionOnly attribute will make sure you cannot go to this page by navigating and that this view must be rendered as a partial, thus by a parent view. cfr: Using ChildActionOnly in MVC
You can go to method of same controller..using this line , and if you want to pass some parameters to that action it can be done by writing inside ( new { } )..
Note:- you can add as many parameter as required.
#Html.ActionLink("MethodName", new { parameter = Model.parameter })

MVC4 - Form data and refreshing on a dynamically rendered view

Been working on creating an interface to allow a modular approach to the UI, the background:
Allows users to drag and drop a module onto a div
jQUery posts back to controller with the module and panel names
Controller returns a JsonResult containing a view that has been rendered, specific to that module
Here is a picture of the UI so you can sort of see what I am doing:
Image
Now, what I am trying to do, is in that JsonResult (Which contains a string output of a view rendering), is save some data back to the model, and refresh that dynamically rendered view, so that just the panel (Where the view has been rendered) updates.
Sounds complicated i know, so here is some code:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult AddModule(string id, string returnTo)
{
string content = RenderView(id);
return Json(new { Target = returnTo, Content = content });
}
private string RenderView(string moduleName)
{
string result = "";
ContentModule module = (ContentModule)Activator.CreateInstance(Type.GetType("TrustMRM.BLL.ContentModules." + moduleName + ",TrustMRM.BLL"));
module.TrustID = Settings.Default.TrustID;
module.DataBind();
this.ViewData.Model = module;
using (var sw = new System.IO.StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(this.ControllerContext, moduleName);
var viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
viewResult.View.Render(viewContext, sw);
result = sw.GetStringBuilder().ToString();
}
return result;
}
The above is what handles the 'drop' of the module. I have an abstract class, ContentModule, and an implementation called BLLForumModule, there is a matching view, BLLForumModule.cshtml, that gets built, and returned in that string, strongly bound tot he BLLForumModule.
What is rendered is a drop down list, equal to some data to configure that particular module:
#model TrustMRM.BLL.ContentModules.BLLForumModule
#{
Layout = null;
}
#if (Model.IsConfigured)
{
<span>I am configured</span>
}
else
{
using (Html.BeginForm("RefreshModule", "Home"))
{
<h3 class="panelHeader">#Html.DisplayTextFor(m => m.Title)</h3>
<span>Select group</span>
#Html.DropDownListFor(m => m.SelectedGroupID, Model.GroupSelection.Select(t => new SelectListItem { Text = t.GroupName, Value = t.GroupID.Value.ToString() }));
#Html.HiddenFor(x => x.ModuleID);
<input type="submit" value="Ok" />
}
}
Now, I am unsure of what to return, or how to handle this post in order to refresh that view, the one that was rendered as a string and sent back, any insight into this, and if anyone has done something similar before, perhaps my rendering the view to a string is the wrong approach?
The code to accept the form post:
public ActionResult RefreshModule(string ModuleID)
{
return View();
}
(Doesn't work)
Something like that will help you
Using Ajax.BeginForm with ASP.NET MVC 3 Razor
Just use Ajax.BeginForm and provide an id of replaced element.
Attach validation after ajax request here
MVC3 Unobtrusive Validation Not Working after Ajax Call

Categories

Resources