I'm using ASP.Net MVC 5, and I want to pass data from the controller to the view WITHOUT adding it to the URL.
I've tried it like this:
public ActionResult Index(LoginViewModel loginViewModel)
{
var landingPgVm = new LandingPgViewModel();
landingPgVm.ElectionName = loginViewModel.ElectionName;
landingPgVm.LandingPageTitle = loginViewModel.LandingPageTitle;
landingPgVm.LandingPageMessage = loginViewModel.LandingPageMessage;
return View("Landing", landingPgVm);
}
And this:
public ActionResult Index(LoginViewModel loginViewModel)
{
var landingPgVm = new LandingPgViewModel();
landingPgVm.ElectionName = loginViewModel.ElectionName;
landingPgVm.LandingPageTitle = loginViewModel.LandingPageTitle;
landingPgVm.LandingPageMessage = loginViewModel.LandingPageMessage;
ViewData["lpvm"] = landingPgVm;
return View("Landing");
}
And still, I get this:
http://localhost:nnnnn/Landing?VotingIsOpen=False&UserIp=%3A%3A1&BrowserAgent=Mozilla%2F5.0%20%28Windows%20NT%2010.0%3B%20Win64%3B%20x64%29%20AppleWebKit%2F537.36%20%28KHTML%2C%20like%20Gecko%29%20Chrome%2F73.0.3683.103%20Safari%2F537.36&ElectionId=1&LoginId=********&LoginPin=*********&ElectionName=2019%20Member-at-Large%20Board%20Election&LandingPageTitle=Success%21&LandingPageMessage=Landing%20Page%20MESSAGE
So sorry that I let my frustration at, what turned out to be MYSELF, spill over onto these pages.
It's been some time since I've done a 'standard' MVC site and forgot how the logic is supposed to flow. (Sometimes it takes getting all the way to posting to SO before I finally figure out/realize the error(s) of my way(s)).
Thanks to info found on the MS docs site here (https://learn.microsoft.com/en-us/aspnet/mvc/overview/security/create-an-aspnet-mvc-5-web-app-with-email-confirmation-and-password-reset), namely, the POST method example under the "You must also update the HttpPost Login action method:" text, I've got it figured out.
I am currently being taught how to use MVC and my supervisor showed me how to use a repository with a read function but I'm stuck with implementing an Add function. This is my current code, thanks in advance!
Repository:
public void AddDriver(DriverModel model)
{
using (var db = new VehicleReservationEntities())
{
var newDriver = new Driver();
newDriver.DriverLastName = model.DriverLastName;
newDriver.DriverFirstName = model.DriverFirstName;
newDriver.DriverLicense = model.DriverLicense;
newDriver.LicenseExpiry = model.LicenseExpiry;
newDriver.MobileNumber = model.MobileNumber;
newDriver.BusinessUnit = model.BusinessUnit;
newDriver.DateRegistered = model.DateRegistered;
db.Driver.Add(newDriver);
db.SaveChanges();
}
}
Controller:
public ActionResult Add()
{
var repo = new VehicleRepository();
var data = repo.AddDriver();
var DVM = new DriverViewModel();
DVM.DriverLastName = data.DriverLastName;
DVM.DriverFirstName = data.DriverFirstName;
DVM.DriverLicense = data.DriverLicense;
DVM.LicenseExpiry = data.LicenseExpiry;
DVM.MobileNumber = data.MobileNumber;
DVM.BusinessUnit = data.BusinessUnit;
DVM.DateRegistered = data.DateRegistered;
db.Driver.Add();
db.SaveChanges();
}
There seems to be a few issues with what you've posted. I think you're looking for something like the following:
Controller:
[HttpPost]
public ActonResult Add(DriverViewModel DVM)
{
var repo = new VehicleRepository();
var driver = new Driver();
//tools such as automapper or tinymapper are often used so that you dont
//need to manually make these assignments
driver.DriverLastName = DVM.DriverLastName;
driver.DriverFirstName = DVM.DriverFirstName;
driver.DriverLicense = DVM.DriverLicense;
driver.LicenseExpiry = DVM.LicenseExpiry;
driver.MobileNumber = DVM.MobileNumber;
driver.BusinessUnit = DVM.BusinessUnit;
driver.DateRegistered = DVM.DateRegistered;
repo.AddDriver(driver);
//return whatever view you want to go to after the save
return View("Index");
}
Repository:
public void AddDriver(Driver newDriver)
{
using (var db = new VehicleReservationEntities())
{
db.Driver.Add(newDriver);
db.SaveChanges();
}
}
a few notes: normally, if you're using viewmodels then these viewmodels are posted to the controller instead of the raw EF entities. You were also calling db.SaveChanges in the controller as well as the repository which doesn't seem like what you want. DbSets are also normally pluralized so your call to add the driver to the db would look like db.Drivers.Add(newDriver). You've also shown 3 different classes related to Drivers: Driver, DriverModel and DriverViewModel. Sometimes this is necessary if your architecture has things separated out into multiple different layers for data access, business logic, and web however I don't see any evidence of that here. If everything exists in one project, I'd probably stick to DriverViewModel and Driver where Driver is the EF entity and DriverViewModel is what your views use and pass back to the controller
First, some context:
Language - C#
Platform - .Net Framework 4.5
Project type - ASP.Net MVC 4
I am trying to determine which View in an MVC project is handling an explicit call to the following method. The MSDN docs for the method are here: http://msdn.microsoft.com/EN-US/library/dd492930.aspx
protected internal ViewResult View(
Object model
)
The original Author is using a View to generate a PDF file with a third-party library. I need to modify the view to include additional information.
The problem: I'm having trouble finding which View to modify. There are hundreds of them, and (IMHO) they are poorly named and organized. The basic process for generating a PDF looks like this. I'm getting confused in between steps 3 and 4.
An Entity's ID is passed to an ActionResult
The Entity is retrieved from the backing store
The model is passed to the Controller.View method mentioned above:
var viewModel = View(model);
var xmlText = RenderActionResultToString(viewModel);
The resulting ViewResult is used with an instance of ControllerContext to generate HTML as if being requested by a browser.
The resulting HTML is passed to the third-party tool and converted to a PDF.
I understand everything else very clearly. What I don't understand is how the call to View(model) determines which View file to use when returning the ViewResult. Any help greatly appreciated!
I'm including the code below, in case it helps anybody determine the answer.
The ActionResult:
public ActionResult ProposalPDF(String id, String location, bool hidePrices = false)
{
var proposal = _adc.Proposal.GetByKey(int.Parse(id));
var opportunity = _adc.Opportunity.GetByKey(proposal.FkOpportunityId.Value);
ViewData["AccountId"] = opportunity.FkAccountId;
ViewData["AccountType"] = opportunity.FkAccount.FkAccountTypeId;
ViewData["Location"] = location;
ViewData["HidePrices"] = hidePrices;
return ViewPdf(proposal);
}
The ViewPDF method:
protected ActionResult ViewPdf(object model)
{
// Create the iTextSharp document.
var document = new Document(PageSize.LETTER);
// Set the document to write to memory.
var memoryStream = new MemoryStream();
var pdfWriter = PdfWriter.GetInstance(document, memoryStream);
pdfWriter.CloseStream = false;
document.Open();
// Render the view xml to a string, then parse that string into an XML dom.
var viewModel = View(model);
var xmlText = RenderActionResultToString(viewModel);
var htmlPipelineContext = new HtmlPipelineContext();
htmlPipelineContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
//CSS stuff
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
var cssResolverPipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlPipelineContext, new PdfWriterPipeline(document, pdfWriter)));
var xmlWorker = new XMLWorker(cssResolverPipeline, true);
var xmlParser = new XMLParser(xmlWorker);
xmlParser.Parse(new StringReader(xmlText));
// Close and get the resulted binary data.
document.Close();
var buffer = new byte[memoryStream.Position];
memoryStream.Position = 0;
memoryStream.Read(buffer, 0, buffer.Length);
// Send the binary data to the browser.
return new BinaryContentResult(buffer, "application/pdf");
}
The RenderActionResultToString helper method:
protected string RenderActionResultToString(ActionResult result)
{
// Create memory writer.
var sb = new StringBuilder();
var memWriter = new StringWriter(sb);
// Create fake http context to render the view.
var fakeResponse = new HttpResponse(memWriter);
var fakeContext = new HttpContext(System.Web.HttpContext.Current.Request, fakeResponse);
var fakeControllerContext = new ControllerContext(new HttpContextWrapper(fakeContext), this.ControllerContext.RouteData, this.ControllerContext.Controller);
var oldContext = System.Web.HttpContext.Current;
System.Web.HttpContext.Current = fakeContext;
// Render the view.
result.ExecuteResult(fakeControllerContext);
// Restore data.
System.Web.HttpContext.Current = oldContext;
// Flush memory and return output.
memWriter.Flush();
return sb.ToString();
}
I'm not exactly sure what you're asking, but, when you call View(model) the view that is chosen is based upon conventions.
Here is an example:
public class HerbController : Controller {
public ActionResult Cilantro(SomeType model) {
return View(model)
}
}
That will look for a view file called Cilantro.cshtml in a folder called Herb (Views/Herb/Cilantro.cshtml). The framework will also look in the Shared directory as well in case it is a view that is meant to be shared across multiple results.
However, you may also want to look at the Global.asax file to see if there are any custom view paths being setup for the view engine. The example I gave above is based upon the default conventions of ASP.NET MVC. You can override them to meet your needs better if needed.
The convention for views is that they are in a folder named after the controller (without "Controller") and the .cshtml file inside that folder is named after the calling action. In your case, that should be:
~/Views/[Controller]/ProposalPdf.cshtml
The logic to determine which view template will be used is in the ViewResult that is returned from the call
var viewModel = View(model);
And how the view is selected is determined by the configured ViewEngine(s), but it will use the current Area, Controller and Action route values to determine what view should be served.
What the route values are for the ProposalPDF action will depend on how your routing is configured, but assuming the defaults, the action route value will be ProposalPDF, the controller route value will be the name of the controller class in which this action resides (minus the Controller suffix) and the area will be the area folder in which the controller lives, with a value of empty string if in the default controller folder. Then using these route values, a view will be looked up in the Views folder using the following convention
~/Views/{Area}/{Controller}/{View}.cshtml
There is always Glimpse that can help with providing runtime Diagnostics too, such as which View file was used to serve up the returned page, although I'm not sure how this would look when a ViewResult is executed internally to provide the contents of a file.
I have a large MVC 4 site that is broken into one project per MVC Area. We use RazorGenerator to pre-compile all of our views into the project assembly for deployment and use the PrecompiledMvcEngine for our ViewEngine.
I have just created a new Area that I would like to share the Shared views from another assembly, but I get an InvalidOperationException when trying to locate a Partial View and none of the DisplayTemplates or EditorTemplates appear to be found either.
I believe it is similar to the issue described in this question.
My code in the RazorGenerator App_Start is like this:
var assemblies = new List<Tuple<string, Assembly>>()
{
Tuple.Create("Areas/Area1", typeof(ABC.Project1.AreaRegistration).Assembly),
Tuple.Create("Areas/Area2", typeof(ABC.Project2.AreaRegistration).Assembly),
};
// Get rid of the default view engine
ViewEngines.Engines.Clear();
foreach ( var assembly in assemblies )
{
var engine = new PrecompiledMvcEngine(assembly.Item2, assembly.Item1) {
UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal
};
// Allow sharing of Area1 Shares views with Area2
if (assembly.Item1 == "Areas/Area2")
{
var sharedPaths = new[] { "~/Areas/Area1/Views/Shared/{0}.cshtml" };
engine.ViewLocationFormats = engine.ViewLocationFormats.Concat(sharedPaths).ToArray();
engine.MasterLocationFormats = engine.MasterLocationFormats.Concat(sharedPaths).ToArray();
engine.PartialViewLocationFormats = engine.PartialViewLocationFormats.Concat(sharedPaths).ToArray();
}
ViewEngines.Engines.Insert(0, engine);
VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
}
When I encounter a partial reference in a view within Area2 like #Html.Partial("Partials/Footer"), I get the exception. It appears that Razor is looking for the correct path
System.InvalidOperationException: The partial view 'Partials/Footer' was not found or no view engine supports the searched locations. The following locations were searched:
~/Areas/Area2/Views/Home/Partials/Footer.cshtml
~/Areas/Area2/Views/Shared/Partials/Footer.cshtml
~/Views/Home/Partials/Footer.cshtml
~/Views/Shared/Partials/Footer.cshtml
~/Areas/Area1/Views/Shared/Partials/Footer.cshtml
at System.Web.Mvc.HtmlHelper.FindPartialView(ViewContext viewContext, String partialViewName, ViewEngineCollection viewEngineCollection)
Looking at the source code of the PrecompiledMvcEngine, it appears that it only looks for views within the assembly.
I initially thought that the view system would look across all registered ViewEngines when trying to resolve a path, but that seems to be an incorrect assumption (and I can see why one would not do that).
Is there a way to share the views across multiple assemblies?
Update
I've worked around the issue by creating a custom version of the PrecompiledMvcEngine that takes a list of assemblies in its constructor. The core change is this:
_mappings = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
foreach (var kvp in assemblies)
{
var baseVirtualPath = NormalizeBaseVirtualPath(kvp.Key);
var assembly = kvp.Value;
var mapping = from type in assembly.GetTypes()
where typeof(WebPageRenderingBase).IsAssignableFrom(type)
let pageVirtualPath = type.GetCustomAttributes(inherit: false).OfType<PageVirtualPathAttribute>().FirstOrDefault()
where pageVirtualPath != null
select new KeyValuePair<string, Type>(CombineVirtualPaths(baseVirtualPath, pageVirtualPath.VirtualPath), type);
foreach (var map in mapping)
{
_mappings.Add(map);
}
}
Any better alternative or pitfalls with this approach?
I want to call the #Html.ActionLink method inside a c# function to return a string with a link on it.
Something like this:
string a = "Email is locked, click " + #Html.ActionLink("here to unlock.", "unlock") ;
Assuming that you want to accomplish this in your controller, there are several hoops to jump through. You must instantiate a ViewDataDictionary and a TempDataDictionary. Then you need to take the ControllerContext and create an IView. Finally, you are ready to create your HtmlHelper using all of these elements (plus your RouteCollection).
Once you have done all of this, you can use LinkExtensions.ActionLink to create your custom link. In your view, you will need to use #Html.Raw() to display your links, to prevent them from being HTML encoded. Here is the necessary code:
var vdd = new ViewDataDictionary();
var tdd = new TempDataDictionary();
var controllerContext = this.ControllerContext;
var view = new RazorView(controllerContext, "/", "/", false, null);
var html = new HtmlHelper(new ViewContext(controllerContext, view, vdd, tdd, new StringWriter()),
new ViewDataContainer(vdd), RouteTable.Routes);
var a = "Email is locked, click " + LinkExtensions.ActionLink(html, "here to unlock.", "unlock", "controller").ToString();
Having shown all of this, I will caution you that it is a much better idea to do this in your view. Add the error and other information to your ViewModel, then code your view to create the link. If this is needed across multiple views, create an HtmlHelper to do the link creation.
UPDATE
To address one.beat.consumer, my initial answer was an example of what is possible. If the developer needs to reuse this technique, the complexity can be hidden in a static helper, like so:
public static class ControllerHtml
{
// this class from internal TemplateHelpers class in System.Web.Mvc namespace
private class ViewDataContainer : IViewDataContainer
{
public ViewDataContainer(ViewDataDictionary viewData)
{
ViewData = viewData;
}
public ViewDataDictionary ViewData { get; set; }
}
private static HtmlHelper htmlHelper;
public static HtmlHelper Html(Controller controller)
{
if (htmlHelper == null)
{
var vdd = new ViewDataDictionary();
var tdd = new TempDataDictionary();
var controllerContext = controller.ControllerContext;
var view = new RazorView(controllerContext, "/", "/", false, null);
htmlHelper = new HtmlHelper(new ViewContext(controllerContext, view, vdd, tdd, new StringWriter()),
new ViewDataContainer(vdd), RouteTable.Routes);
}
return htmlHelper;
}
public static HtmlHelper Html(Controller controller, object model)
{
if (htmlHelper == null || htmlHelper.ViewData.Model == null || !htmlHelper.ViewData.Model.Equals(model))
{
var vdd = new ViewDataDictionary();
vdd.Model = model;
var tdd = new TempDataDictionary();
var controllerContext = controller.ControllerContext;
var view = new RazorView(controllerContext, "/", "/", false, null);
htmlHelper = new HtmlHelper(new ViewContext(controllerContext, view, vdd, tdd, new StringWriter()),
new ViewDataContainer(vdd), RouteTable.Routes);
}
return htmlHelper;
}
}
Then, in a controller, it is used like so:
var a = "Email is locked, click " +
ControllerHtml.Html(this).ActionLink("here to unlock.", "unlock", "controller").ToString();
or like so:
var model = new MyModel();
var text = ControllerHtml.Html(this, model).EditorForModel();
While it is easier to use Url.Action, this now extends into a powerful tool to generate any mark-up within a controller using all of the HtmlHelpers (with full Intellisense).
Possibilities of use include generating mark-up using models and Editor templates for emails, pdf generation, on-line document delivery, etc.
You could create an HtmlHelper extension method:
public static string GetUnlockText(this HtmlHelper helper)
{
string a = "Email is locked, click " + helper.ActionLink("here to unlock.", "unlock");
return a;
}
or if you mean to generate this link outside of the scope of an aspx page you'll need to create a reference to an HtmlHelper and then generate. I do this in a UrlUtility static class (I know, people hate static classes and the word Utility, but try to focus). Overload as necessary:
public static string ActionLink(string linkText, string actionName, string controllerName)
{
var httpContext = new HttpContextWrapper(System.Web.HttpContext.Current);
var requestContext = new RequestContext(httpContext, new RouteData());
var urlHelper = new UrlHelper(requestContext);
return urlHelper.ActionLink(linkText, actionName, controllerName, null);
}
Then you can write the following from wherever your heart desires:
string a = "Email is locked, click " + UrlUtility.ActionLink("here to unlock.", "unlock", "controller");
There's a couple things bad about these other answers...
Shark's answer requires you to bring the LinkExtensions namespace into C#, which is not wrong, but undesirable to me.
Hunter's idea of making a helper is a better one, but still writing a helper function for a single URL is cumbersome. You could write a helper to help you build strings that accepted parameters, or you could simply do it the old fashion way:
var link = "Email is... click, to unlock.";
#counsellorben,
i see no reason for the complexity; the user wants only to render an Action's routing into a hard string containing an anchor tag. Moreover, ActionLink() in a hard-written concatenated string buys one nothing, and forces the developer to use LinkExtensions whidh are intended for Views.
If the user is diehard about using ActionLink() or does not need (for some reason) to calculate this string in the constructor, doing so in a view is much better.
I still stand by and recommend the answers tvanfosson and I provided.
Your best bet is to construct the link manually using the UrlHelper available in the controller. Having said that, I'm suspicious that there is probably a better way to handle this in a view or partial view, shared or otherwise.
string a = "Email is locked, click <a href=\""
+ Url.Action( "unlock" )
+ "\">here to unlock.</a>";
Maybe try this:
string a = "Email is locked, click " + System.Web.Mvc.Html.LinkExtensions.ActionLink("here to unlock.", "unlock");