I am using ASP .Net MVC 4.0 and VS10. I am a newbie in web application.
I have designed a page with html razor view. Here is some code of Index.cshtml:
#{
ViewBag.Title = "BAP Automation";
}
#section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
<form action="Index">
<table> **//EDITED BELLOW**
<tr><form action="" method="post">
<td>Upload Excel File: </td>
<td><input type="text" name="NAMEtxtFileName"/></td>
<td><input type="button" value="Upload" id="IDbtnUpload" name="NAMEbtnUpload"/></td>
</form>
</tr>
<tr>
<td>Company Name: </td>
<td><input type="text" /></td>
<td></td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" value="Process" /></td>
<td></td>
</tr>
</table>
</form>
</div>
</section>
}
I am trying to upload an excel file in NAMEbtnUpload's click event. clicking on this button we will be in this page, just a file upload dialog will open and selecting the file, the file location will be shown in the NAMEtxtFileName textbox.
EDIT 1:
I have written some code from the suggested code:
[HttpPost]
public ActionResult Index(HttpPostedFileBase NAMEbtnUpload)
{
if (NAMEbtnUpload.ContentLength > 0)
{
var fileName = Path.GetFileName(NAMEbtnUpload.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/Given Excel's"), fileName);
NAMEbtnUpload.SaveAs(path);
}
return RedirectToAction("Index");
}
but this shows following error:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /
Try adding the "EncType" attribute to your form.
#using (Html.BeginForm("ACTION", "CONTROLLER", FormMethod.Post, new { EncType="multipart/form-data"})){
//FORM MARKUP HERE
}
Phil Haack shows you how to handle file uploads with his blog post Uploading a File (Or Files) With ASP.NET MVC.
There is quite a bit of stuff you are missing so reading that post will get you further than any answer here.
** UPDATE FOR EDIT 1 **
A couple issues
<form action="index" > - this should be <form action="/ControllerName/Index">
You have multiple form tags that are nested. You can have multiple form tags but they can't be nested. In your case your only need one. Most of the time you only need 1.
<input type="button" value="Upload" id="IDbtnUpload" name="NAMEbtnUpload"/> should be
It is more conventional to use #using(Html.BeginForm()) as opposed to manually writing form tags. See below.
#using(Html.BeginForm("Index"))
{
<table>
<tr>
<td>Upload Excel File: </td>
<td><input type="text" name="NAMEtxtFileName"/></td>
<td><input type="file" id="IDbtnUpload" name="NAMEbtnUpload"/></td>
</tr>
<tr>
<td>Company Name: </td>
<td><input type="text" /></td>
<td></td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" value="Process" /></td>
<td></td>
</tr>
</table>
}
clicking on [the upload] button we will be in this page, just a file upload dialog will open and selecting the file, the file location will be shown in the NAMEtxtFileName textbox.
That is not possible because a file upload element is not accessible programatically, anymore. "Back in the days" it was, and malicious sites silently uploaded sensitive information by setting the file upload control's value to well known password file locations and so on.
You'll just have to put an <input type="file" /> on your form and handle the upload serverside, as suggested in the link on #Bretts answer.
Set the name of file control in controller class.
for example in above code
public ActionResult Index(HttpPostedFileBase NAMEbtnUpload)
change NAMEbtnUpload to NAMEtxtFileName
this resolve your problem.
Related
I have a strange issue in my blazor app. I don't know why but when I navigate from a specific path of my app to another path then I get a 400 disconnect message in my browser console.
When I navigate back to the entry point the connection becomes established again.
There are these paths right now
/
/Admin/Users
/Admin/Users/{name}
Admin/Users shows me a list of all employees from my SQL-Database.
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>E-Mail</th>
<th>Status</th>
<th>Aktion</th>
</tr>
</thead>
<tbody>
#foreach (var mitarbeiter in UserManager.Users)
{
<tr>
<td>#mitarbeiter.FirstName #mitarbeiter.LastName</td>
<td>#mitarbeiter.Email</td>
<td></td>
<td>
<a href="/Admin/Users/#mitarbeiter.UserName" class="btn btn-primary">
<i class="fa fa-edit"></i>
</a>
</td>
</tr>
}
</tbody>
</table>
As you can see, each employee has a a-Tag to /Admin/Users/{name}. When I click on it, everything works as expected. When I use the navigation now to go back to /Admin/Users then the connection will be terminated. It becomes established again when I go to / or to /Admin/Users manually again.
The navigation is defined as:
<AuthorizeView Roles="Administratoren">
<Authorized>
<div class="sb-sidenav-menu-heading">System</div>
<nav class="sb-sidenav-menu-nested nav">
<NavLink href="/Admin/Users" class="nav-link">Benutzer</NavLink>
</nav>
</Authorized>
</AuthorizeView>
The page /Admin/Users/{name} just displays some razor components to edit the employee. All sites uses the same default layout which contains the blazor.server.js
<script src="/_framework/blazor.server.js"></script>
Does anybody know, how I can fix this issue or what is causing it?
Thanks in advance!
To fix this issue, I added the following code to my _Host.cshtml
<base href="~/" />
How do you handle the Id in a detail page with the newest ASP.NET Core 2.2 technology?
If I use a hiden field with the Id it gets passed when I click on save.
But when I comment it I wont get the Id.
<form asp-controller="Coach" asp-action="UpdateCoach" method="post">
#*<input asp-for="Coach.Id" type="hidden" />*#
<table class="table table-bordered table-condensed">
<tr>
<td>Naam:</td>
<td><input asp-for="Coach.CoachName" value="#Model.Coach.CoachName" /></td>
</tr>
<tr>
<td>Type coach:</td>
<td>
<select asp-for="Coach.CoachTypeId" asp-items="#(new SelectList(Model.CoachTypes,"Id", "CoachTypeDescription"))">
<option></option>
</select>
</td>
</tr>
<tr>
<td>Telefoon:</td>
<td><input asp-for="Coach.CoachPhone" value="#Model.Coach.CoachPhone" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input asp-for="Coach.CoachEmail" value="#Model.Coach.CoachEmail" /></td>
</tr>
</table>
<input type="submit" value="Opslagen" class="btn btn-default" />
This is my Controller :
[HttpPost]
public async Task<IActionResult> UpdateCoach(CoachViewModel coachViewModel)
{
return Redirect("/Coach/Coach");
}
In coachViewModel I get all values expect the Id!
How do you handle the Id in a detail page
Assuming this is an "edit" page for an entity that already exists in a database, then your options include:
Store it in a hidden field so it's included in the POST.
Use it as a URI path parameter or querystring parameter
e.g. GET /users/{userId} and PSOT /users/{userId} or GET /users?userId={userId} and POST /users?userId={userId}
If the Id value can be determined from the current request (e.g. based on a User's security Claim or something in session-state) then use that.
If this is a page to define data for a new entity that doesn't exist yet (assuming you're using IDENTITY/AUTO_INCREMENT), then it doesn't matter because you'll be doing an INSERT operation anyway and you should have a separate URI path (and Controller Action) for this operation anyway (i.e. so your code doesn't expect nor require any entity identifier in this scenario).
There is a mvc application, in which I am trying to modify in pre-compiled CSHTML page(Index.cshtml)
#using System.Web.Mvc.Html
#model Services.Admin.ViewModels.IndexViewModel
#{
Layout = "~/Views/Admin/_Layout.cshtml";
ViewBag.Title = Resources.AdminResources.Index_Title;
}
<div class="container">
<div class="masonry">
<div class="item col-lg-4 col-md-4 col-sm-4">
<h3>Event Clinics</h3>
<table class="table table-striped table-bordered table-hover">
<tbody>
<tr>
<td class="max-width">
#Html.ActionLink("Premier Instructors", "Index", "PremierInstructor")
</td>
<td></td>
</tr>
<tr>
<td class="max-width">
#Html.ActionLink("Reports", "Index", "Reports")
</td>
<td></td>
</tr>
<tr>
<td class="max-width">
#Html.ActionLink("Users", "Index", "Users")
</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
Here is also respective Index.generated.cs, in which all code is written with help of "WriteLiteral".
When I am trying to add/modify in .cshtml form, it's impact not showing on UI.
I have also find out on various sites and found that these cshtml is already compiled using "RazorGenerator" tools.
Now My problem is this, when I am going to make any changes in this type of cshtml file, it is not reflected on screen.
In case of RazorGenerator based pre-compiled .cshtml forms as there is need to modify it's html then follow below steps.
Right Click on .chstml file (ex. index.cshtml).
Click on "Properties".
Under "Advanced" section remove "RazorGenerator" from "Custom Tool" option.
DO CHANGES IN CSHTML FILE.
Again follow above 1,2 steps.
Under "Advanced" section add "RazorGenerator" in "Custom Tool" option.
Save form and run it.
Now you will be seeing all the changes in UI.
how to perform an action when i click the html submit button without using runat server. Where i have to write the code and what i have to write. Please help me. I have a below code:
<table>
<tr>
<td>Enter User Id</td>
<td><input type="text" id="txtUserId" name="userId"/></td>
</tr>
<tr>
<td>Enter Password</td>
<td><input type="password" id="txtPassword" name="password"/></td>
</tr>
<tr>
<td>
<input type="checkbox" id="chkRememberMe" />
<label for="chkRememberMe">Remember Me</label>
</td>
</tr>
<tr>
<td><input type="Submit" id="btnSubmit" value="Login" name="submitButton"/></td>
</tr>
</table>
I want to write logic in *aspx.cs file. Thank you.
Any http post of a page back to the server will trigger your codebehind to be executed, regardless of whether you have a runat="server" or not. You can detect this by inspecting the IsPostback property of the Page object.
All asp.net buttons are "submit" buttons. Typically, you'll want to have a runat="server" attribute on your button so you can handle events for that specific button in your codebehind. While I can only think of a few select reasons for not, the primary one typically cited is that the runat="server" causes the control ID to be changed so that it is unpredictable in client scripts and CSS. If this is your reason, you can set the clientidmode to static on that control.
I have a simple form. Its got one field and a submit button.
I hide the submit button. The submit button is actually triggered with an anchor
tag that calls a javascript method that uses jQuery to get the element and execute
a click(). This works fine, the form posts and record is successfully written into the DB.
So now I added xVal for validation. I am trying to add in the simple client side validation.
It doesn't work when I click the anchor tag. However, if I un-hide the submit button and try posting the form with that instead of using the anchor tag that's calls the js method, it does work. So basically I am trying to figure out why it doesn't work when I use the js method to trigger the click of the submit button.
Any grande ideas? Thanks much!
Heres some code...
<div id="manufacturerButtons" class="moduleRow">
<%= Html.ActionImage(Url.Content("~/Content/Icons/bullet_go_back.png"), "Back To Admin", "Admin", "Admin")%>
| <a class="actionImage" href="javascript: addManufacturer();">
<img border="0" src="<%= Url.Content("~/Content/Icons/accept.png")%>"> <span>Add
Manufacturer </span></a>
</div>
<div class="moduleContent">
<div id="manufacturerContainer">
<div class="moduleRow">
<h3>
New Manufacturer</h3>
</div>
<div class="moduleRow">
<% Html.BeginForm("NewManufacturer", "Admin", FormMethod.Post); %>
<table class="noBorder" border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 125px">
<h6>Name:</h6>
</td>
<td>
<%= Html.TextBox("Name") %>
</td>
</tr>
<tr style="display: none;">
<td>
</td>
<td>
<input type="submit" id="btnAdd" name="btnAdd" />
</td>
</tr>
</table>
<% Html.EndForm(); %>
<%= Html.ClientSideValidation<EquipmentManufacturer>() %>
</div>
</div>
Javascript:
function addManufacturer() {
//$('form').submit(); // doesnt work when trying to validate either
$('#btnAdd').click();
return true;
}
What you need to do is trigger the jQuery validation on your form. Try:
$('form').validate();
To submit the form upon successful validation, try:
$('form').validate({ submitHandler: function(form) { form.submit(); } });
Note that 'form' should be a valid jQuery selector for your form...