I am working on a test mvc project and since it's my 1st time working in mvc environment I am almost lost and is completely different compared to asp.net web forms.
I am trying to put a textbox and a button on a form, but when I am using <%= Html.TextBox("name") %> for textbox for example, the code displays as a text on the screen and is not rendered as a textbox. When I am using html markup for textbox and button I can see the textbox but shouldn't <%= Html.TextBox("name") %> be correct way to do that?
Here is what I have here:
#{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Welcome to my Web Site!";
}
<p>
ASP.NET Web Pages make it easy to build powerful .NET based applications for the web.
Enter your name: <%= Html.TextBox("name") %>
<input id="Text1" type="text" />
<input id="Button1" type="button" value="button" />
</p>
Which way should I go, can I go with the standard html format or what am I doing wrong that the textbox from <%= Html.TextBox("name") %> doesn't get displayed?
Thanks in advance, Laziale
You are using ASPX syntax. For Razor, it would be something like this:
#Html.TextBox("TextBoxName")
So your code would look like:
<p>
ASP.NET Web Pages make it easy to build powerful .NET based applications for the web.
Enter your name:
#Html.TextBox("name")
<input id="Button1" type="button" value="button" />
</p>
In addition to the previous answers, if you are referencing a Model on your View page, then you can use the Razor HTML Helpers with Lambda expressions.
Updated Example (This update is in response to the Laziale's comment):
In your Models directory you have a User class:
namespace MvcApplication.Models
{
public class User
{
public string Name { get; set; }
}
}
In your Controllers directory, you have a UserController:
namespace MvcApplication.Controllers
{
public class UserController : Controller
{
//
// GET: /User/
public ActionResult Index()
{
return View();
}
}
}
In your Views directory, you have a sub-directory named "User" which contains an "Index.cshtml" file:
#model MvcApplication.Models.User
#using (Html.BeginForm())
{
#Html.TextBoxFor(x => x.Name)
<input type="submit" />
}
MVC/Razor will create the following HTML:
<html>
<head>...</head>
<body>
<form action="/User" method="post">
<input id="Name" name="Name" type="text" value="" />
<input type="submit" />
</form>
</body>
</html>
You use the Razor syntax which is denoted using # at the start:
#Html.TextBox("name")
Related
I'm trying to understand how Razor pages work, as well as .Net Core, by creating a small web application and I'm stuck on how to handle the button action within a form. I'm used to the MVC type of process (from when I first tried web apps 5 years ago) where the button would have a onClick action that could be accessed from the code behind but it seems like that's not the same with a Razor page (unless I'm just not seeing it). I have a basic form like this
<form method="post">
<fieldset>
<input type="text" value="" placeholder="user name"/>
<input type="password" value="" placeholder="password"/>
<input type="button" value="Submit" id="submitButton"/>
</fieldset>
So what I'm trying to achieve is when the button is pressed an action in the .cs file is called that will perform a couple different operations (like calling an API, getting a result and then depending on result route to a different page) but even if I add an "onClick" to the button I can't figure out how to hook it up to the code behind. I've seen various answers, most using models and a database but since that's not the same as what I'm doing those examples haven't helped.
I will try to make a simple example for you. Create a razor page and use the name "Test". The Test.cshtml file should have the following contents:
#page
#model WebApplication1.Pages.TestModel
<form method="post">
<fieldset>
<input asp-for="username" placeholder="user name" />
<span asp-validation-for="username" class="text-danger"></span>
<br />
<input asp-for="password" type="password" placeholder="password" />
<span asp-validation-for="password" class="text-danger"></span>
<br />
<input type="submit" value="Submit" id="submitButton" />
</fieldset>
</form>
The Test.cshtml.cs should have the following contents
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace WebApplication1.Pages
{
public class TestModel : PageModel
{
[BindProperty]
public string username { get; set; }
[BindProperty]
public string password { get; set; }
public void OnGet()
{
// you can initialize the values. for example I set the username
username = "test";
}
public IActionResult OnPost()
{
// do something with username and password
if (string.IsNullOrEmpty(password))
{
ModelState.AddModelError("password", "Password is a required field.");
return Page();
}
// or you can redirect to another page
return RedirectToPage("./Index");
}
}
}
Tell me if you need extra explanation for this example. I hope it helps.
I have a problem with using an ajax button in a partial view to update a div in the parent page. If I put the same button into the parent page it works fine. Is this not possible or am I missing something? cheers for the help
Parent View:
<div id="topiclist">
#{Html.RenderPartial("DetailLoader", this.Model);}
</div>
Partial View
#using (Ajax.BeginForm("LatestTopics", "Forums", new AjaxOptions { UpdateTargetId = "topiclist" }))
{
<input type="hidden" name="page" value="#ViewBag.page" />
<input type="submit" id="refresh" class="latestbuttons" value="#(ViewBag.NewTopics) New Topics" />
}
Include this line in your views, I had the same issue and it worked for me !
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
I have a small websolution that needs the user to input a password. I have two input boxes
<input type="password" runat="server" id="m_txtPassword1"/>
If I set some chars to the Value-property of the control like this:
m_txtPassword1.Value="someChars";
The password box is rendered empty. No bullets are shown. If I look into the rendered html-source, also no value-tag has been rendered. If I change the type to
<input type="text" runat="server" id="m_txtPassword1"/>
the chars are shown. Is this by design? How can I disable this feature?
Please note, I don't want to put a real password into the value-property, I only want to show the user that there is already a password set, and this is IMO done best with some 8 bullets in the input-control. But for this, I need the possibility to set the value-property of the control.
Update
For all, having the same problem: I have tried to declare <asp:textbox id="m_txtPassword1" runat="server" TextMode="Password" /> with the same result. Also m_txtPassword1.Attributes["value"]="someChars" has not helped.
It seems that this is realy not possible.
As a workaround, I declared the password-boxes as plain html without the runat="server" and have set the value-property in markup (via two properties from the code-behind). Not nice but I really want to show the user that he has already entered a password.
Another workaround would be to set the value through javascript on load.
This is by default. You cannot set a password.
I make this works,
<html>
<head>
<script type="text/javascript">
function alertValue()
{
alert(document.getElementById("password1").value);
}
function setpassword()
{
password1.value="someChars";
}
</script>
</head>
<body>
<form>
<input type="password" id="password1" value="" />
<input type="button" id="button1" onclick="alertValue()" value="Show default value" />
<input type="button" id="button2" onclick="setpassword()" value="Set value" />
</form>
</body>
</html>
Try this:
http://jsbin.com/ocexo5
It is by design, for security reasons - so that the password is not in the
HTML in plain text.
Now, you could write out javascript to set the value property of the textbox
on the client, of course this would still mean that you have the password in
plain text in the HTML.
Here is example of the page:
Markup:
<script type="text/javascript">
function setPwd()
{
var Pwd = "<%=Pwd %>";
var txtText = document.getElementById("MainContent_txtText");
txtText.value = Pwd;
}
</script>
<input type="password" id="txtText" runat="server"/>
And code-behind:
public partial class _Default : System.Web.UI.Page
{
public string Pwd;
protected void Page_Load(object sender, EventArgs e)
{
Pwd = "password";
ClientScript.RegisterStartupScript( this.GetType(),"somescript","setPwd();",true);
}
}
Textbox11.Attributes.Add("Value",whatever_your_password_is)
Given the following view model and action using the DefaultModelBinder, it seems to ignore the dictionary, but bind all other properties correctly. Am I missing something here? Looking at the MVC source code this seems legit.
Thanks
public class SomeViewModel
{
public SomeViewModel()
{
SomeDictionary = new Dictionary<string, object>();
}
public string SomeString { get; set; }
public IDictionary<string, object> SomeDictionary { get; set; }
}
[HttpPost]
public ActionResult MyAction(SomeViewModel someViewModel)
{
//someViewModel.SomeString binds correctly
//someViewModel.SomeDictionary is null
}
<%# Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<SomeViewModel>" MasterPageFile="~/Views/Shared/Site.Master" %>
<asp:Content runat="server" ID="Content2" ContentPlaceHolderID="MainContent">
<% using (Html.BeginForm("MyAction", "MyController")) {%>
<%= Html.EditorFor(m => m.SomeString) %>
<%= Html.EditorFor(m => m.SomeDictionary["somevalue"]) %>
<input type="submit" value="Go" />
<%} %>
</asp:Content>
And for reference, the HTML output is:
<input class="text-box single-line" id="SomeString" name="SomeString" type="text" value="" />
<input class="text-box single-line" id="Somedictionary_somevalue_" name="SomeDictionary[somevalue]" type="text" value="" />
EDIT: The above will not work as pointed out below, however I prefer this layout and the following quick hack works for my needs, call this just after posting...
someViewModel.SomeDictionary = (from object key in Request.Form.Keys
where key.ToString().StartsWith("SomeDictionary[")
select new
{
Key = key.ToString().Replace("SomeDictionary[", string.Empty).Replace("]", string.Empty),
Value = (object)Request.Form[key.ToString()]
}).ToDictionary(arg => arg.Key, arg1 => arg1.Value);
It needs some tidying up ofcourse :)
You may take a look at this post to see how dictionaries should be binded. I am afraid that using strongly typed EditorFor helpers you won't be able to achieve this and you will have to generate the fields manually.
I'm trying to figure out a way to create a page that can be used for generic forms. What i had in mind was someone here at our office would use the obout edit to create html that would look like a form. This html would be saved to a database. When the user wanted to fill out the form and mail it, they would click on the correct form retrieval and this html would be put into a label control. So now the page has a label control on it with some html as the text of the label. The user could type in the values that they wanted. So the html might look something like this:
<p style="margin: 0px; text-align: center;">
Quarterly Report of Employees Serverd</p>
<br />
<br />
Employee:
<input type="text" style="width: 300px; height: 22px;" />
<br />
<br />
Address:
<input type="text" style="width: 300px; height: 22px;" />
<br />
<br />
<br />
The user would type in the input type="text" a value of say John Smith and then type into the address input type as well.
Now I want to grab all this html and mail it off. I know how to do the mailing portion, but the grabbing the html I'm not getting. I can grab the html in the label, but the text that that user typed in is not included in that text. So how do I get that html and the text the user typed in. Any ideas.
thanks
shannon
You need to encode the html to store them securely.
Use literal control instead of label or text controls.
Check this link for the first option.
Thanks :)
and you can use a way like this :
<input id="textField" type="text" runat="server"/>
C# - Code Behind
Mail.Send(textField.Value);
and don't forget to use ValidateRequest="false" in the header section of asp.net..
:)
You can iterate through the Request items to get the submitted values. If you want to send of an email which substitutes the entered values for the HTML input fields, you'll have to parse out the form HTML to find your input fields:
<input type="text" id="firstName" name="firstName"
style="width: 300px; height: 22px;" />
And then replace it with
Request.Form["firstName"]
Notice that the input fields will need identifiers so you can retrieve them from the HTTP request.
Hope this helps!
For one thing, you're really going to want to get a little more information into your html - at the very least some name attributes on the form elements:
Employee: <input type="text" name="employee" />
This way, you could create an aspx page like:
<%# Page language="C#"
autoeventwireup="true"
codebehind="DynamicForm.aspx.cs"
inherits="TempWebApp.DynamicForm" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal id="m_HtmlForm" runat="server"></asp:Literal>
<asp:Button id="m_SubmitForm"
onclick="SubmitForm_OnClick"
runat="server"
text="Submit" />
</div>
</form>
</body>
</html>
Then in your code you read your html from the database into the .Text of the literal control:
using System;
using System.Web.UI;
namespace TempWebApp
{
public partial class DynamicForm : Page
{
protected void Page_Load(object sender, EventArgs e)
{
m_HtmlForm.Text = getFormData();
}
protected void SubmitForm_OnClick(object sender, EventArgs e)
{
// Just showing we've picked up the form data.
// You'll also see ViewState and others in here.
foreach (string key in Request.Form.AllKeys)
{
m_HtmlForm.Text += string.Format("<br />Key: <b>{0}</b><br />Value:<br />{1}<br />", key, Request.Form[key]);
}
}
private string getFormData()
{
// Excluded for brevity
}
}
}
Obviously, in your button/postback handler, you would need to ensure you have the original HTML from the database, and then either modify the input elements to add a text attribute to them with the value, or more likely, replace them with the actual values - otherwise you'll have to do lots of additional parsing of the form if your users start saving forms with radio buttons, check boxes, select lists, etc.