I want to fetch data from text file that is in particular folder into div tag..
MVC is new for me..So explain me briefly..
controller
public ActionResult filexist()
{
string subPath = "~/Content/74/74/6_Hall0/Text/data.txt";
bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));
if (!exists)
System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
else
{
}
return View();
}
HTML:
<form action="" method="post">
<div>
<textarea rows="3" cols="15" contenteditable="true" name="data"></textarea>
<input type="submit" value="Submit" />
</div>
</form>
first of all,
the default Method in the controller is "GET",
so if you want to use Post so you have to do like this:
in your Controller add "[HttpPost]":
[HttpPost]
public ActionResult filexist()
{
string subPath = "~/Content/74/74/6_Hall0/Text/data.txt";
bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));
if (!exists)
System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
else
{
}
return View();
}
and then, in your HTML(View):
#using (Html.BeginForm("filexist", "Your_Controller_Name", FormMethod.Post))
{
<div>
<textarea rows="3" cols="15" contenteditable="true" name="data"></textarea>
<input type="submit" value="Submit" />
</div>
}
Related
I have a basic form for which I want to handle buttons inside the form by calling the ActionResult method in the View's associated Controller class. Here is the following HTML5 code for the form:
<h2>Welcome</h2>
<div>
<h3>Login</h3>
<form method="post" action= <!-- what goes here --> >
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
</form>
</div>
<!-- more code ... -->
The corresponding Controller code is the following:
[HttpPost]
public ActionResult MyAction(string input, FormCollection collection)
{
switch (input)
{
case "Login":
// do some stuff...
break;
case "Create Account"
// do some other stuff...
break;
}
return View();
}
you make the use of the HTML Helper and have
#using(Html.BeginForm())
{
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
}
or use the Url helper
<form method="post" action="#Url.Action("MyAction", "MyController")" >
Html.BeginForm has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:
#using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
< ... >
}
If you don't specify any arguments, the Html.BeginForm() will create a POST form that points to your current controller and current action. As an example, let's say you have a controller called Posts and an action called Delete
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
return View(model);
}
[HttpPost]
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
if(model != null)
db.DeletePost(id);
return RedirectToView("Index");
}
and your html page would be something like:
<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>#Model.Title</strong> will be deleted.</p>
#using(Html.BeginForm())
{
<input type="submit" class="btn btn-danger" value="Delete Post"/>
<text>or</text>
#Url.ActionLink("go to list", "Index")
}
Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.
<a href="Controller/ActionMethod">
<input type="button" value="Click Me" />
</a>
Adding parameters:
<a href="Controller/ActionMethod?userName=ted">
<input type="button" value="Click Me" />
</a>
Adding parameters from a non-enumerated Model:
<a href="Controller/ActionMethod?userName=#Model.UserName">
<input type="button" value="Click Me" />
</a>
You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!
Below is the form code
#{
ViewData["Title"] = "ModelTrain";
ViewBag.Center = true;
}
<form method="post" class="text-center" asp-controller="Home" asp-action="Index">
<div class="form-group text-center w-50 mx-auto">
<input type="text" name="url" class="form-control my-2" id="url" placeholder="Добавить ссылку профиля " />
</div>
<input type="submit" value="Обучмть модель" class="submit btn btn-secondary" />
</form>
And Below is the Controller code
public class HomeController : Controller
{
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Index(String url)
{
ControlObject control = new ControlObject();
control.body_profile = url;
control.profile = true;
var json = JsonConvert.SerializeObject(control);
var firebaseClient = new FirebaseStorage("hackathontest-e8d57.appspot.com");
var path = #"C:\Users\emiol\source\repos\HackathonFiles\HackathonFiles\TextFile1.txt.txt";
System.IO.File.WriteAllText(path, json);
using (FileStream fs = System.IO.File.Open(path, FileMode.Open))
{
var result = await firebaseClient.Child("TextFileForUrls.txt").PutAsync(fs);
}
return RedirectToAction("Index","Image");
}
}
}
`
It returns a 404 error when i try to post back to the form. This doesn't happen when testing locally. can someone point me to a possible solution please as I've been stuck for a long time on this
Try removing div class and have your form code like below:
#{
ViewData["Title"] = "ModelTrain";
ViewBag.Center = true;
}
<form method="post" asp-controller="Home" asp-action="Index">
<input type="text" name="url" class="form-control my-2" id="url" placeholder="Добавить ссылку профиля " />
<input type="submit" value="Обучмть модель" class="submit btn btn-secondary" />
</form>
Most probably, your form code is incorrectly written and some classes are incorrectly interpreted. Try the below basic approach first and then add your custom changes one by one and see where it fails (if the above does not work).
Check out this tutorial for reference: https://www.aspsnippets.com/Articles/ASPNet-Core-Form-Submit-Post-Example.aspx
I am looking for a solution on how to send a file using a form to an asp application. I am writing in the asp .net framework MVC Razor.
My form:
<div class="container">
<div class="col-md-2">
#using (Html.BeginForm("Data", "Admin", FormMethod.Post, new { encrypte = "multipart/form-data"}))
{
<div class="form login-form">
<label for="username" class="text-info">Wczytaj plik:</label>
<input type="file" name="file" id="file" />
</div>
<div id="register-link" class="text-right">
<input type="submit" class="btn btn-success" value="Importuj" />
</div>
#ViewBag.Message
}
</div>
</div>
My controller:
[HttpPost]
public ViewResult Data(HttpPostedFile file = null)
{
if(file != null && file.ContentLength > 0)
{
string path = Path.Combine(Server.MapPath("~/Upload/Data"), Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "Succes";
}
return View("AdminDataView", students);
}
Unfortunately, the above code does not work, am I doing something wrong with it, is there another option to upload the file to asp?
I think there is a typo and i suggest you that use ActionResult instead of ViewResult.
Defference between ActionResult & ViewResult
the typo is: new { enctype="multipart/form-data"}) not new { encrypte = "multipart/form-data"})
Sample Code:
View
#using(Html.BeginForm("UploadFile","Upload", FormMethod.Post, new {
enctype="multipart/form-data"}))
{
<div>
#Html.TextBox("file", "", new { type= "file"}) <br />
<input type="submit" value="Upload" />
#ViewBag.Message
</div>
}
Controller
[HttpPost]
publicActionResultUploadFile(HttpPostedFileBase file)
{
try
{
if (file.ContentLength > 0)
{
string _FileName = Path.GetFileName(file.FileName);
string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
file.SaveAs(_path);
}
ViewBag.Message = "File Uploaded Successfully!!";
return View();
}
catch
{
ViewBag.Message = "File upload failed!!";
return View();
}
}
Please refer below link this gives you better understanding.
https://stackoverflow.com/a/60519052/7761461
Hope this will surely help you.
HttpPostedFileBase always provides null, I looked online various solutions but the result does not change, I am attaching the code, can you help me?
being that I already have a model in my view I asked myself if it is possible to do this, I do not have to upload more than one file.
ps: I also tried to change the style of the input but it is not changed
I apologize if the English is bad but I have translated with the translator of google
#model WebElementware.Models.TAB_LAVORA_CON_NOI
#{
ViewBag.Title = "WorkWithUs";
}
<form action="#Url.Action("WorkWithUs","Home")" method="post" enctype="multipart/form-data">
#using (Html.BeginForm("WorkWithUs", "Home", FormMethod.Post, new { TBLCN = Model, enctype = "multipart/form-data"}))
{
<label for="file">Inviaci il tuo curriculum:</label>
<input type="file" name="file" id="file" />
}
</form>
<section>
<center>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Cerca!" class="btn btn-default" />
</div>
</div>
</center>
</section>
controller
[HttpPost]
public ActionResult WorkWithUs(TAB_LAVORA_CON_NOI TBLCN ,HttpPostedFileBase file)
{
string Message = "";
if (ModelState.IsValid)
{
TBLCN.LETTO = false;
using (DB_WEB_ELEMENTWAREEntities1 DB = new DB_WEB_ELEMENTWAREEntities1())
{
DB.TAB_LAVORA_CON_NOI.Add(TBLCN);
DB.SaveChanges();
}
}
else
{
Message = "Invalid Request";
}
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
file.SaveAs(path);
}
ViewBag.Message = Message;
return View(TBLCN);
}
I have a single asp.net page it contains a number of tabs and a datetime picker.
When the user selects a date from the datetime picker and clicks on the update button it does that it should do but it does not return the user to the same tab.
HTML Code
<ul class='tabs'>
<li><a href='#tab1'>Production</a></li>
<li><a href='#tab2'>Page2</a></li>
<li><a href='#tab4'>Page3</a></li>
<li><a href='#tab6'>Page4</a></li>
</ul>
<div id='tab1'>
<hr />
<div class="ProductionDiv">
<label class="ProductionLabel">Production Data</label>
#{
using (Html.BeginForm("UpdateProductionData", "Home", FormMethod.Post))
{
<h3>Date :</h3> <input type="text" id="dp4" name="dp4"/>
<input type="submit" value="Update"/>
}
}
</div>
<div id='tab2'>
<hr />
<div class="ProductionDiv">
<label class="ProductionLabel">Production Data</label>
#{
using (Html.BeginForm("UpdateProductionData", "Home", FormMethod.Post))
{
<h3>Date :</h3> <input type="text" id="dp4" name="dp4"/>
<input type="submit" value="Update"/>
}
}
</div>
<div id='tab3'>
<hr />
<div class="ProductionDiv">
<label class="ProductionLabel">Production Data</label>
#{
using (Html.BeginForm("UpdateProductionData", "Home", FormMethod.Post))
{
<h3>Date :</h3> <input type="text" id="dp4" name="dp4"/>
<input type="submit" value="Update"/>
}
}
</div>
<div id='tab4'>
<hr />
<div class="ProductionDiv">
<label class="ProductionLabel">Production Data</label>
#{
using (Html.BeginForm("UpdateProductionData", "Home", FormMethod.Post))
{
<h3>Date :</h3> <input type="text" id="dp4" name="dp4"/>
<input type="submit" value="Update"/>
}
}
</div>
C# code
I do what i need to do and return to the Index form is there any way to specify what tab to return too.
return View("Index");
How about using hidden field + jquery, like this:
Update your ViewModel and add an int property for example LastTabIndex, then Add a hidden field to your form:
#Html.HiddenFor(m=>m.LastTabIndex)
and then use jquery :
<script type="text/javascript">
$(function() {
$(".tabs").tabs({
create: function() {
var index = 0;
if (Modernizr.localstorage) {
if (localStorage.getItem("LastTabIndex") === null) {
localStorage.setItem("LastTabIndex", 0);
} else {
index = localStorage.getItem("LastTabIndex");
}
} else {
index = $('#LastTabIndex').val();
}
$(".tabs").tabs("option", "active", index);
},
activate: function() {
var sel = $('.tabs').tabs('option', 'active');
$("#LastTabIndex").val(sel);
if (Modernizr.localstorage) {
localStorage.setItem("LastTabIndex", sel);
}
}
});
});
</script>
EDIT: I've updated my code to use a hybrid solution (localstorage and if local storage is unsupported then use hidden field).
Hope this helps!
Regards,
Uros