0

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.

1 Answers1

0

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/

mongesh madhavan
  • 583
  • 4
  • 16
  • You got me wrong. I want to create new view. For this I need to create a file and action in a controller which is working perfectly in by provided code. As the view is not included in my application it shows 404. After including if I run then it works. – Vidhyadhar Galande Jun 16 '16 at 09:35