Verification Successful

Обратиться к html asp

Gray Pipe

Answered by:

Question

Answers

yes i know , i am try ListItem object add new item on javascript but i cant acces all ListItem object

Based on your description, it seems that there is a ListBox on the Asp.net page. You add items to it dynamically with JavaScript. However, you want to get the items on the server side? If this is the case, I suggest you refer to these code below: These code demonstrate how to add HtmlInputBox with JavaScript and get the values which you typed.

 head runat="server"> title>Untitled Pagetitle> script type="text/javascript"> window.onload=function() < document.getElementById("InserMore").attachEvent("onclick",InsertRow) >function InsertRow() < var varnames = document.getElementsByTagName("input") var LenItem = varnames.length+1 var vtep = document.createElement("input") vtep.type="Text" vtep.id= "varBox"+LenItem document.body.appendChild(vtep); >function saveItems() < var lastitem=""; var varnames = document.body.getElementsByTagName("input") for(var o=0;ovarnames.length;o++) < if(varnames[o].id.indexOf("varBox")>-1) < lastitem+=varnames[o].value+"|" >> if(lastitem.length>0) < lastitem=lastitem.substring(0,lastitem.length-1) document.getElementById("HiddenField1").value=lastitem >return true > script> head> body> form >"form1" runat="server"> div> asp:HiddenField >"HiddenField1" runat="server" /> a href="#" >"InserMore">Click for morea> asp:Button >"Button1" runat="server" Text="Save" OnClientClick="javascript:return saveItems()" onclick="Button1_Click"/> div> form> body> html>
 
protected void Button1_Click(object sender, EventArgs e) < string strList = this.HiddenField1.Value; string[] strA = strList.Split(new string[] < "|" >, StringSplitOptions.None); foreach (string str in strA) < Response.Write(str + "<br>"); > >

Источник

Returning HTML or any file using Asp.Net controller

I have updated this post to take asp.net core into consideration. If you are looking for an answer on how to do this in Web API in .Net Framework look further below in this post.

How to return HTML from an API controller in ASP.Net core and .Net 5+

First off, I would suggest you use cshtml (Razor) and fire up a standard web page project template in your IDE if you wish to make a website. However if your use case is that you need to return HTML from an API Controller for whatever reason, here is what you need to do.

Let us say we have the following HTML:

If this file is located in a folder Content, we can return its content from a controller using the following:

In the above we get the contents using File.ReadAllText and return it using the ContentResult in ASP.Net core. The result is the following when you visit /index :

How to return HTML from a Web Api controller in .Net framework

I will start by mentioning that Web API is not meant to deliver HTML pages. If you wish to build a website please use regular MVC - or something else. With that being said, you can have different reasons for having to do this.

Below is an example of a controller that returns the content of a html file.

The above example is getting the path for the file through the HttpContext using MapPath. If you are not using IIS, then maybe you will only need to use Directory.GetCurrentDirectory() .

For this project I have the below structure in my project. I can get the html file by using the endpoint http://localhost:52774/api/web/helloworld

Structure of the project

That is it!

I hope you enjoyed this post on how to return HTML from a controller, please let me know in the comments if you did!

Peter Daugaard Rasmussen

Programmer, Developer, Consultant.

Источник

How to Return HTML From ASP.NET Core Web API

How to Return HTML From ASP.NET Core Web API

A typical web API returns JSON or XML responses. However, rare cases exist where we need to return responses in other formats. In this article, we are going to learn how to return HTML from ASP.NET Core Web API. We will also state some use cases for this type of API.

Return HTML From ASP.NET Core Web API

We return HTML from an ASP.NET web API endpoint by specifying a return type of ContentResult :

[HttpGet] public ContentResult Index() < var html = "

Welcome to Code Maze

"; return new ContentResult < Content = html, ContentType = "text/html" >; >

Here, we create an endpoint that returns the HTML with the text “Welcome to Code Maze”.

The ContentResult class has three properties; Content , ContentType and StatusCode . For HTML response, we create a ContentResult instance and populate the ContentType property with "text/html" .

Use ControllerBase.Content Method

We can only use this method for controllers that derive from ControllerBase . Let’s see what we mean by that:

public class UserController : ControllerBase

The ControllerBase.Content() method returns a ContentResult object. This method has several overloads, and we will be using an overload that accepts two string parameters. The first string represents the content of the HTML while the last is the content-type which for HTML is "text/html" .

Let’s see how we can use this method:

[HttpGet("verify")] public ContentResult Verify() < var html = "
Your account has been verified.
"; return base.Content(html, "text/html"); >

Since our controller derives from ControllerBase , we simply call base.Content() and pass the required parameter to return the desired HTML.

Returning Static HTML

For static HTML, the content of the page is the same for all the visitors. If the HTML we intend to render is static, we can read it from an HTML file directly.

First, we create our static HTML file within our project:

      

Profile Verified

Thank you for verifying your profile.

Then we read the content and return its result:

[HttpGet("confirm-verify")] public ContentResult ConfirmVerify() < var html = System.IO.File.ReadAllText(@"./assets/verified.html"); return base.Content(html, "text/html"); >

In this case, we place our static HTML named “verified.html” within the assets folder in the root directory of our project. By doing this we make our code more readable. This comes in handy when we display HTML with large content.

Returning Dynamic HTML

Dynamic HTML like the name suggests will show different contents for different viewers. Since we already know that we pass our HTML content as a string we can manipulate it that way. For readability, we are going to create a separate HTML file as we did in our previous example:

Finally, let’s create our API endpoint:

[HttpGet("welcome")] public ContentResult Welcome(string name) < var html = WelcomeHTML(name); return base.Content(html, "text/html"); >

We just create an API endpoint that returns a dynamic page while making our code as readable as possible.

When Do We Want to Return HTML From ASP.NET Core Web API

Let’s inspect some use cases where we will return HTML from an API:

One of the use cases would be when we want to provide feedback on an account or profile confirmation after the users click on the link sent to their email.

Also, another use case is when we display content for solutions without a front end. For example, an API As A Service without a front-end can use this to display some important information such as Terms and Conditions or receipts in the case of an e-commerce API.

Источник

Обратиться к html asp

On first glance, our HTML form looks reasonable. We’ve got a single text box (firstName) and the form is going to send its data via an HTTP Post. Unless we indicate otherwise, this will post back to the same location used to serve the form. So, using default routing conventions, we could use a controller like this…

public class FormController : Controller < [HttpGet] public IActionResult Index() < return View(); > [HttpPost] public IActionResult Index(string firstName) < return Content($"Hello "); > > 

We’ll see our form if we browser to http:///form . When we submit the form, it will be posted to the same address ( http:///form ) (as an HTTP Post request). But, we have a fatal flaw in our form! Run this, enter a name, submit the form and all you’ll get is a half-complete sentence. For the value of the input to be submitted as form data, it needs to have a name attribute.

input type="text" id="firstName" placeholder="Your name goes here" name="firstName" /> 

With the name attribute in place, ASP.NET MVC spots the incoming “firstName” value (in the submitted form data) and binds it to the firstName parameter we specified in the Index (POST) method on our controller. Diagnose form data problems When you come across issues like this, it isn’t always obvious what’s causing the problem. This is where the Chrome network tab comes into its own. Submit your form with the developer tools open (F12) and you’ll see the form post in the network tab. Click the relevant request and check out the Form Data section. In this example you can see that firstName has been submitted as form data and so should be available to ASP.NET Core. If you don’t see the values you expect then the chances are your form isn’t working properly and that’s where to focus your efforts on fixing the problem.

#2 Using Tag Helpers

Now we know how to manually set up our forms to post the right data, correctly tagged so our MVC controllers know how to handle it. But this seems like a bit of a faff (and is asking for trouble every time we rename anything either in the HTML or the C#). With ASP.NET Core you have an alternative. You can use Tag Helpers to save you manually adding name attributes to all of your input fields. First up, create a class to act as the model for our page.

public class FormModel < public string FirstName < get; set; > > 
@model FormBasics.Controllers.FormModel 

When you try this for yourself, make sure you specify the correct namespace, where your model exists. With that in place, we can start using tag helpers to do some of the plumbing (e.g. adding name attributes) we’d otherwise have to do ourselves.

form asp-action="Index" asp-controller="Form"> label asp-for="FirstName">label> input asp-for="FirstName" placeholder="Your name goes here"/> input type="submit" /> form> 

We’ve made a few changes here. First we’ve explicitly defined the action and controller that this form will post back to, using asp-action and asp-controller . This isn’t strictly necessary, but it doesn’t hurt to be explicit, just in case we start moving things around, the form will continue to post to the correct controller action. Secondly, because this page now knows about its model, we can use the asp-for tag helper on our input and label elements, specifying the relevant property name from our model. Here’s the resulting form. And here’s how this will be rendered (it’s often worth taking a look at the source code in your browser to see what HTML we end up with in cases like this).

form action="/Form" method="post"> label for="FirstName">First Namelabel> input placeholder="Your name goes here" type="text" id="FirstName" name="FirstName" value=""> input type="submit"> input name="__RequestVerificationToken" type="hidden" value=""> form> 

Note how ASP.NET has picked up that the rendered form should make a POST to /form and has automatically included the name attribute for the input field. If you’re wondering what the __RequestVerificationToken is, this is a neat way to reduce the risk of your application being duped by a cross site request forgery attack.

I’ve got a model and I’m not afraid to use it

Now we’ve got a model we can get rid of that string parameter in the Index POST action and replace it with a FormModel parameter.

[HttpPost, ValidateAntiForgeryToken] public IActionResult Index(FormModel model) < return Content($"Hello "); > 

ASP.NET MVC Core will bind the form data to your model automatically. This also means we won’t find ourselves constantly updating the Index action every time we need to handle another value submitted via the form. Incidentally, I’ve also added the other half of the Request Verification Token check here (the ValidateAntiForgeryToken attribute) to make sure this form has been posted from our site (and not a malicious site hosted by someeone else).

A better label

Finally, by default the asp-for tag helper on our label has used the name of the property for its value. We can improve this and be explicit about what the label should say, with an attribute on our model.

public class FormModel < [DisplayName("First Name")] public string FirstName < get; set; > > 

Admittedly, this form isn’t going to win any prizes for its design, but at least the label reads a little better!

What about HTML Helpers?

If you’ve used previous versions of MVC, you’re probably familiar with the HTML Helpers from previous versions. They look like this… @Html.TextBox("firstname") One huge benefit of Tag Helpers over HTML Helpers, is that they leave you free to define your markup using standard HTML tags. Rather than have some magic render the entire element for you, the tag helper extends your standard HTML element. This is evident in our example where we are free to add a placeholder attribute to the FirstName input without jumping through extra hoops to bend an HTML Helper to our will.

In Summary

Lean on ASP.NET Core’s Tag Helpers to get your forms up and running. Wire up your inputs (text boxes etc) to something on the model (using Tag Helpers) and the value entered by the user will be submitted as formdata when the user submits the form. ASP.NET Core’s model binding will then kick in and assign the posted values to an instance of the Model. From here, you can do whatever you need to with the model (including saving it to a database etc.)

One last step.

Thanks for being a subscriber

Did you know? You can access additional tutorials, videos, and download source code from the subscribers vault.

Источник

Читайте также:  Вызвать функцию python из другого файла
Оцените статью