I am trying to create new view using Asp.Net MVC. My view created successfully along with respective changes in my controller but
it shows 404 error as the view is not included in project.
After including if I am trying to run this and hit url/controller/Action its working perfectly.
My code is as follows for creating view and adding action in controller
// My main aim is to create new page dynamically
[HttpPost]
public ActionResult Index(Content model)
{
var fileName = model.Name; // validate to check the same name don't exist.
if (!System.IO.File.Exists(fileName))
{
System.IO.File.Create(Server.MapPath("~/Views/Custom/"+fileName+".cshtml"));
}
//start Append data in custom controller
var lines = System.IO.File.ReadAllLines(Server.MapPath("~/Controllers/CustomController.cs"));
System.IO.File.WriteAllLines((Server.MapPath("~/Controllers/CustomController.cs")), lines.Take(lines.Length - 2).ToArray());
//start Append data in custom controller
//System.IO.File.WriteAllLines((Server.MapPath("~/Controllers/CustomController.cs")), "public ActionResult'" + fileName + "'(){");
string appendData = "public ActionResult "+ fileName+ "() \n { \n";
appendData += "return View();";
appendData += " \n } \n } \n }";
System.IO.File.AppendAllText((Server.MapPath("~/Controllers/CustomController.cs")), appendData);
objcontext.objContent.Add(model);
objcontext.SaveChanges();
ModelState.Clear();
return View();
}
Please help me how to include the file dynamically where I don't need to do manual include.
You can achieve dynamic controller by loading Assembly during execution. But writing a cs class, it won't work.
Have a look at below approach
http://www.strathweb.com/2012/06/using-controllers-from-an-external-assembly-in-asp-net-web-api/
Related
I need to use &mdash (more beautiful as par my UI/UX designer), instead of regular '-' .
My question is how do I jam this html dash &mdash inside my controller where I am setting my pageHeading and BrowserTitle.
I am working with an MVC application, the code below is the controller which gets the result and then bundles up and sends it to the view.
In the View the PageHeading comes up automatically:
public ActionResult View()
{
var dto = _service.GetByID(id);
base.BrowserTitle = "Reports - " + report.ReportDisplayName;
base.PageHeading = "Reports - " + report.ReportDisplayName;
return View(dto);
}
In my controller, I am rendering a view.
My Action method looks like this:
public ActionResult SomePrint(Model model)
{
//Some business action
return View("viewname",model);
}
Now my requirement is to save this view as file(may be pdf file) in my solution and send it to print and delete the file once the print is done.
Tried to use Rotativa and convert it to pdf by following
public ActionResult DownloadViewPDF()
{
var model = new GeneratePDFModel();
//Code to get content
return new Rotativa.ViewAsPdf("GeneratePDF", model){FileName = "TestViewAsPdf.pdf"}
}
But i need it to save it as pdf and print the same.
Any help? Thanks in advance.
If you would have been requesting to export to a known convertible type (such as Excel), formatting the stream would be enough. But if you would like to Export to PDF you should create another View to Export the file and use a 3rd party application such as iText.
You can use BuildPdf method on ViewAsPdf.
public ActionResult DownloadViewPDF()
{
var model = new GeneratePDFModel();
var pdfResult = new ViewAsPdf("GeneratePDF", model)
{ FileName = "TestViewAsPdf.pdf" };
var binary = pdfResult.BuildPdf(this.ControllerContext);
// you can save the binary pdf now
return File(binary, "application/pdf");
}
as I can make this code dynamically
public ActionResult EditingUpdate()
{
//...
string fName = GridViewExtension.GetEditValue<string>("FirstName");
string lName = GridViewExtension.GetEditValue<string>("LastName");
//...
}
There are several ways of doing this, it depends on how you want to present the action to the user. I would recommend you follow the example on the DevExpress Demo Page. They show you how to pass the model into your controller.
Controller:
public ActionResult EditingUpdate(MyObject model)
{
string fName = model.FirstName;
....
....
{
Now, the following step is where you have few choices. You can call the controller method in several different ways, all from the gridview partial view. Again, refer to the DevExpress Demo Page. If you want to call the method from an edit action (which is what I assume based on your method name), then you use:
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "MyController", Action = "EditingUpdate" };
But there are other ways of calling this method, such as
settings.CustomActionRouteValues = new { Controller = "MyController", Action = "EditingUpdate" };
It all depends when you want the gridview to call this method.
Follow the example in the demo, that will help you decide how you want it. Good luck!
This is a newbie configuration problem I suspect.
See return statement comment in code snippet.
[HttpGet]
public ActionResult TestService()
{
ViewBag.Message = "DataLayer Service";
Service dataLayerService = new Service {CookieContainer = new CookieContainer()};
dataLayerService.SetSessionAppName("SAND");
WebServiceModel webServiceModel = new WebServiceModel();
webServiceModel.Result = dataLayerService.GetSessionAppName();
return this.View(webServiceModel); // <== Cannot resolve View "TestService"
}
Do you have a view called "TestService" that take for parameter a WebServiceModel?
Your web project must contain in the Views folder a folder with the name of the controller and a file called TestService.cshtml.
This file should have in its header
#model WebServiceModel
If you want to be able to use it in the view.
I found the following answer from Darin Dimitrov - In ASP MVC3, how can execute a controller and action using a uri?
var routeData = new RouteData();
// controller and action are compulsory
routeData.Values["action"] = "index";
routeData.Values["controller"] = "foo";
// some additional route parameter
routeData.Values["foo"] = "bar";
IController fooController = new FooController();
var rc = new RequestContext(new HttpContextWrapper(HttpContext), routeData);
fooController.Execute(rc);
The only problem is that I like to capture the ViewResult that is returned by this Action (to render it as a string), but IController.Execute returns void.
I suspect I can find the Result somewhere in the property of the ControllerContext, but I can't find anything like that. Does anyone have an idea how to do this?
What you want to do, as far as I understand is to actually render the view, get the HTML result and assert against it.
This is practically testing the view which is pretty much not recommended and against most practices.
However, you could come up with some solutions to this. The one presented (simplified and a bit messy) is using RazorEngine to render the view. Since you can't get access to the .cshtml (the view file) from the test project you will need to get to its contents in a messy way.
Install RazorEngine NuGet package to your test project and try something along these lines:
[Fact]
public void Test()
{
var x = new HomeController(); // instantiate controller
var viewResult = (ViewResult)x.Index(); // run the action and obtain its ViewResult
var view = string.IsNullOrWhiteSpace(viewResult.ViewName) ? "Index" : viewResult.ViewName; // get the resulted view name; if it's null or empty it means it is the same name as the action
var controllerName = "Home"; // the controller name was known from the beginning
// actually navigate to the folder containing the views; in this case we're presuming the test project is a sibling to the MVC project, otherwise adjust the path to the view accordingly
var pathToView = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Replace("file:\\", "");
pathToView = Path.GetDirectoryName(pathToView);
pathToView = Path.GetDirectoryName(pathToView);
pathToView = Path.GetDirectoryName(pathToView);
pathToView = Path.Combine(pathToView, "WebApplication5\\Views\\" + controllerName + "\\" + view + ".cshtml");
var html = Razor.Parse(File.ReadAllText(pathToView), viewResult.Model); // this is the HTML result, assert against it (i.e. search for substrings etc.)
}