I am coming from PHP so bear with me with my noobness...
I want to know a few things.
I know PHP, javascript and MySQL very very well now and I understand that browsers understand a few things.. html and javascript.
I ran through a tutorial of c#.net and found that it had pre-made "user controls" and i thought, oh my it's completely different from PHP... Then i realised that in the end it ends up with a bunch of javascript I could have written myself (not saying i want to ;), just saying).
My questions....
1.
If I have a table with some input fields:
<form id="form1" runat="server" method = "post" action = "validate_entry.aspx">
<table>
<tr>
<td>Name: </td><td><input type = "text" name = "name" /></td>
</tr>
<tr>
<td colspan = "2"><input type = "submit" value = "submit" /></td>
</tr>
</table>
</form>
and use the post and action methods, and then in validate_entry.aspx on Page_Load class I call something like:
c.Request["name"];
and do whatever with it.. Is this still a professional way of using c# or am i wanting it to be too much like PHP. Am i missing out on some execute speed or something even though it's running javascript.
2.
If I wanted to simply output the word "arse" in a div... If I do something like this, am I defeating the object of c#.net
<div id = "the_butt_holder">
<% Response.Write("arse"); %>
</div>
or a better example is that in my validate_entry.aspx page I do:
<div id = "the_response">
<% Response.Write(c.Request["name"]); %>
</div>
I think in your case, you would benefit greatly from looking at ASP MVC. It gets much closer to the grain and will probably be much closer to what you're used to working with as you have a great deal of control over the html.
Well James, I think you could start using asp.net mvc. It will be so easier to you than asp.net webforms. WebForms is based on Server Controls and Events, you cannot set a page in tag, instad of it you can create a , double click in it and write your code on .cs file respective of your webform, then, the .net framework will do a thing called PostBack and executes this event. There's a desnecessary long life cycle when a PostBack runs.
In Asp.Net webForms you don't have control of your output HTML code. The SErver Controls will do it for you, and sometimes it is not you want (or need).
With ASP.NET MVC you have a Route Tables and you have a MVC Architecture Pattern, so, if you use a mvc framework in PHP, it would be easy for you. With ASp.NET MVC you have control of your HTML, and you can create Typed Views. Check this link: http://www.asp.net/mvc
I hope it helps you.
Your way is by no means wrong, however there is another way in ASP.NET, which is to use actual TextBox (which renders input field) control instead of input field directly. That way, you will be able to access value as a property of the control.
<asp:TextBox id="tb1" runat="server" />
var text = tb1.Text;
Why not just write literal directly instead of outputting it like this?
<div id = "the_butt_holder">
arse
</div>
You may feel much more at home using ASP.NET MVC, and Razor layout engine. It's much more like PHP and Smarty (or whatever similar templating engine replaced it nowdays :) )
You can find more than enough tutorials right there on the site to get you started.
Related
I need to get the value of an input and pass that to a select2 to get suggestions. How can I call a JavaScript function from a URL action
#* Name *#
<input id="Name" name="AccountName" type="text" value="" autocomplete="off" data-url="#Url.Action("*********", "******")" data-urlonselect="#Url.Action("*****", "*******")">
#* Group / HQ *#
#Html.Select2Ajax("newGroup", Url.Action("******", "****", new { valuefromInput = MyFunction(); }))
I have never used Select2, so there may be some functionality in there that I am unaware of. With that said, the Url.Action() is question is a standard part of the ASP.NET MC framework and I feel relatively comfortable with answering based on that.
Url.Action is a sever side razor directive. That means that all the processing happens on the webserver at the time of the request. It is not, nor can it be, aware of the JavaScript that may execute in the future.
My recommendation would be to create a hidden input, or a non-visible div, and store the output of Url.Action in that container, using a recognizable placeholder for your input value, say "-12." Then, in your javascript that is responding to the changes to the input, you can dynamically replace the place holder with its actual value and set that property accordingly on the select box. You may or may not need to re-initialize your Select2 drop down in with each call.
At least, that is why I would try. Hope this helps! =)
I am still new to the coding field and am having a bit of trouble with a part, hoping someone can help me. I am working on a MVC page where i am trying to move text, the user inputs, around the page to a few pre-set spots and without having to refresh the page. Do i need a type of script for this? And if i do what would be best? Thanks for the help.
You can do it this way.
Enter Text here... <input id="testText" type="text" onKeyUp="javascript:showText($(this), event);"/>
<br/>
<br/>
<br/>
See it here... <span id="testTextSpan"></span>
Then, add this script...
<script type="text/javascript">
var showText = function (el, e) {
$('#testTextSpan').html(el.val());
};
<script>
See it here in this JSFiddle...
http://jsfiddle.net/ZEcNp/
Be sure to include JQuery libraries in your project, or reference the CDN.
If you'd like me to include an example with raw javascript, with no JQuery, I can also provide that for you.
I would recommend jQuery to do all that client-side.
You would just need an ID for each element you would use as the predefined spots, using either .appendTo, .insertAfter, .html, or something else depending on your exact needs.
I am working on a webforms project using c#/aspx/jquery. I'm not sure where to handle my Onclick. Both options (doing it in C# or jquery) seem feasible. Which would be better practice?
Here is the scenario:
I want to build a checkbox which will toggle a textbox's textmode, altering it between Password and SingleLine.
Currently, I have this following code for my markup since I am currently handling it in C#:
<asp:Checkbox ID="CheckBox1" OnCheckedChanged="CheckBox1_OnCheckedChanged"/>
The code:
protected virtual void OnCheckedChange(EventArgs e)
{
If (CheckBox1.TextMode == TextMode.Password)
CheckBox1.TextMode = TextMode.SingleLine;
else
CheckBox1.TextMode = TextMode.Password;
}
The use case of this is: A user is entering his password. On the same page, he may choose to keep the password hidden or not by checking the checkbox.
Which would be better practice?
What is your functional requirement?
Setting this in C# on the asp.net code behind, you will need a post-back to make it work. This means the page will refresh and the text box will change.
On the client (JS/JQuery) the page will not refresh.
Now you evaluate the work required vs the quality you need. (If you want a nice user experience and are ok with writing JS put it in JS, if you're strapped for time and are ok with the refresh then do it on asp.net).
I'm trying to answer your question in general sense about HOW such a decision (in my humble opinion) should be made. Realistically this is very simple to implement in javascript and your should do it there.
Now for the code (I assume you know how to put it in asp.net code behind so I'm going to write the JS approach):
Html:
My Password: <input type="password" id="mytext" /> <br />
Hide Chars : <input id="passChk" type="checkbox" checked="true" />
Javascript:
$(function() {
$("#passChk").change(function(){
if(this.checked) {
$("#mytext").attr("type","password");
} else {
$("#mytext").attr("type","text");
}
});
});
See it running here: http://jsfiddle.net/rC5NW/2/
After trying to implement the accepted answer, I realized that some browsers (I used Google Chrome) does not allow changing the type attribute. There is a way to bypass this but I don't think it is worth it for my purposes:
Therefore, It might be better to just use C#.
Relevant Questions
Does javascript forbid changing the input type from password or to password?
change type of input field with jQuery
I've been working with a team on a ASP.NET project, a project management tool.
Most of the pages is basically writing stuff from the database to the page and store the changes which where made.
This is our first project in ASP.NET (We currently use ASP Classic for all our other projects), our senior told us not to use MVC.
The problem now is that our Designer/Front-end developer is pretty much clueless if it comes to ASP.NET, he also does not want to use VisualStudio if possible (He uses OSX).
For example:
What would for example be the best way to write a dynamic list?
This is what we currently do:
<div id="tasks" overflow-y="scroll" style="height:400px;">
<ul id='taskList'>
<% PrintTasks(); %>
</ul>
</div>
In the code-behind:
public void PrintTasks()
{
foreach (var task in _tasks)
{
Response.Write("<li rel='#' id='task_"+task.TaskID+"'>" +
...
"</span>" +
"</li>");
}
}
In this case, its not possible for the designer to edit the li tags without going into the code behind.
Thanks.
I'm afraid your front-end developer will have to suck it up and learn how to use VS. If your entire team is working on ASP.Net, there is no way to escape the wrath of VS.
MVC is a good for separation of C# and HTML. Razor engine allows a nice way to separate code and markup.
For you list you would probably do something like that in Razor:
#foreach (var item in items)
{
<li rel="#" id ="blah_#item.id">#item.text</li>
}
You should absolutely raise the question why MVC is not an option. It would be a much better fit for what you're doing, and the code quality would therefore also be much better, which helps the project overall. Not to speak of team productivity (and the ability for your designer to "escape" VS).
Doing some CSHTML with Razor you and your team would almost feel "at home".
According to your context, the main friction point is your front end developper.
So, decide on using a javascript framework (Knockout.js, angular.js, whatever).
Let your front-end developer design the UI that will get all needed info from JSON provided by your web stack of choice (ASP.NET MVC, Web Api, whatever).
This will ensure that he can develop his UI with the tool he wants. And you can work on the backend without worrying about UI. You just need to agree on the JSON contracts and stick to them.
This way, you will keep a clean separation of concerns with :
- everyone developping with the tools they're most at ease with
- no layer mix and match (ie having some HTML "generated" in your code behind)
And, your list will look like (using knockout) (syntax may not be accurate):
<ul data-bind="foreach: myList">
<li><span data-bind="text: Text, attr: { id: Id }" /></li>
</ul>
Code behind (using asp.net mvc) (syntax may not be accurate)
public JsonResult GetList()
{
var res = myServiceLayer
.GetListItems()
.Select(
x => new { Text = x.Val, Id = x.Id }
);
return JsonResult( res );
}
When using ASP.NET WebForms, I would give you the following suggestions:
Take advantage of CSS. Accept that your designer will not be able to edit the HTML produced by your code-behind, but if you use CSS intelligently you can probably overcome that challenge. In your example, you have a div and a ul element with id's, and the designer can then change the CSS to style these elements and child elements using the cascading properties of CSS. (Ex: #taskList > li)
Consider client side templating when appropriate. When presenting data for the user, fx. lists, consider using a templating framework. (jQuery fx) These templates can be placed in separate files that your designer can edit without VS. (Reference: load jQuery-Templates from external file?)
Spend some time learning the different controls available in ASP.NET WebForms, instead of using Response.Write to build HTML. Using Response.Write in the code-behind is generally a really bad practice and should be avoided, because your code will quickly turn into spaghetti and be unmaintainable. And if you're hoping to use ASP.NET WebForms (Or MVC) on later projects and want your senior and management to see the advantages of ASP.NET, then you and your team should spend a little time learning the framework. When you do that, you will be rewarded with more structured code that is easier to maintain. But if you use your current Classic ASP practices in ASP.NET, chances are that neither your senior or your management will see the benefits of using ASP.NET. And that would be a shame, because the benefits are really there. :-)
Good luck!
In the specific case you mentionned, in 'classical' asp.net, you're supposed to use a repeater: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater(v=vs.80).aspx
<asp:Repeater id="Repeater1" runat="server">
<ItemTemplate>
<li rel='#' id='task_<%# DataBinder.Eval(Container.DataItem, "TaskID") %>'>
<span>Whatever</span>
</li>
</ItemTemplate>
</asp:Repeater>
Basically, learn which webcontrols are available, create new ones every time it's necessary, and try to get as much as you can from asp.net webform's limited binding/templating system.
use Repeater here:
<asp:Repeater runat="server" ID="r1">
<ItemTemplate>
<li rel='#' id='<%# Eval("id","prefix{0}") %>'><span>
<asp:Label runat="server" ID="t1"><%# Eval("Caption") %></asp:Label>
</span></li>
</ItemTemplate>
</asp:Repeater>
and in cs file:
r1.DataSource=list;
r1.DataBind();
I am looking into binding some data. What method of output would be better. I usually use Gridviews, but I am unsure if the table would be better now.
You should really steer clear of ASP.NET Web Forms controls when using the MVC framework. They don't play nicely together 100% of the time.
The HTML helpers/ standard HTML elements are the replacement. The idea being that you have more control over what you're doing that with Web Forms.
There are some nice grids available:
jqGrid (example of use with MVC here)
And the awesome MVCContrib project.
If all you're looking to do is present(output) a table of data, no need for a gridview at all (besides, in MVC, you most likely wouldn't want to anyway).
Simply loop through your model collection and create a new table row for each item:
<table>
<% foreach (var item in Model) { %>
<tr><td>FieldName</td><td><%= Html.Encode(item.Field) %></tr>
<% } %>
</table>
you can format up your table however you like by applying the appropriate css class to it.
EDIT: a better example to show multiple fields, also showing how to display no data.
<% if (Model.Count() > 0)
{ %>
<table width="35%">
<thead><tr><th>Species</th><th>Length</th></tr></thead>
<% foreach (var item in Model)
{ %>
<tr>
<td><%= item.FishSpecies%></td>
<td align="center"><%=item.Length%></td>
</tr>
<% } %>
</table>
<% }
else
{ %>
No fish collected.
<%} %>
That really depends on what you are outputting.
I only use tables / gridview for tabular data.
For other stuff i use Repeater controller or FormView.
While you can partially use ASP.NET server controls in MVC applications (e.g. a menu will render quite well), you should expect that they won't expose the expected or rich behavior you are used to see in ASP.NET. There's a number of reasons for that:
They typically rely on ViewState (and ControllerState)
You are required to put them inside a form tag with runat="server". Most controls check that this is the case indeed
Related to this, they rely heavily on the postback paradigm, which is not used in ASP.NET MVC
As a typical example of behavior that you won't find back, there is paging and sorting ...
When you delve into it, you soon find out that the helpers available in the MVC framework allow you to generate tabular data quite efficiently ....