Reload MVC2 user control with jQuery - asp.net-mvc-2

I know I've had a ton of questions today, but still trying to get everything under control learning MVC 2 tie right way. Before I get into the question I already tried the solution offered here but I get an 500 internal server error.
So here's what I'm trying to do, I give the user the ability to select from a list of skills (loaded in a ListView user control) or add a new one to the list and select that. The adding new one is completed (using a WCF service & jQuery) but now I'm trying to reload the skills user control.
According to the solution I linked to I added an action to my AccountController
public ActionResult GetSkillControl()
{
return View("~/Views/Shared/SkillsListView.ascx");
}
I have the control inside a span (so it has a container)
<tr>
<td style="vertical-align:top;"><label for="SkillsListView" title="Skills">Skills:</label></td>
<td class="regElements"><span id="SkillListViewContainer"> <% Html.RenderPartial("SkillsListView"); %></span><%= Html.ValidationMessageFor(m => m.Skills, "*")%><br />
<span id="AddSkillError"></span>
Add: <input type="text" id="NewSkill" class="inputbox" style="width:75px;" /> <input type="button" value="Add" id="AddSkill" name="AddSkill" /></td>
<td></td>
</tr>
And in my jQuery ajax call I have
success: function () {
$('#SkillListViewContainer').load('../AccountController/GetSkillControl');
}
It's when it reaches that point that the JavaScript console in Chrome shows it returns a 500 internal server error. What am I missing here?

Based on the standard routes in ASP.NET MVC, try "/Account/GetSkillControl". Anything you use from jQuery's load method must be a valid URL. The route engine is looking or Account and not AccountController. Also by using the leading "/" it will resolving from the root of the site.

Related

Can i use ngxErrors or something like it to display a form error?

I use ngxErrors to display errors for a form control and it works great. Is there any way to get similar functionality for a form or a form group? Currently, I display a form error like this:
<div *ngIf="form.hasError('loginFailed')">
Login Failed
</div>
The bummer is, when I detect that there is a form error (e.g. after the login form is submitted) as opposed to control error, I set it like this:
this.form.setErrors({ loginFailed: true });
this.cdr.detectChanges();
Where this.cdr is an instance of ChangeDetectorRef. This is necessary because I'm using OnPush change detection strategy. So basically it's like calling $scope.$apply() from AngularJS all over again.
What I would really like to do is something more like how ngxErrors does it:
<div ngxErrors="myForm">
<div ngxError="loginFailed" [when]="['dirty', 'touched']">
The login has failed
</div>
But ngxErrors expects myForm to be a control.
This feature is not currently baked into ngxErrors, but I submitted a PR. https://github.com/UltimateAngular/ngxerrors/pull/18
The working syntax is a slight modification of the above:
<div ngxErrors>
<div ngxError="loginFailed" [when]="['dirty', 'touched']">
The login has failed
</div>
</div>
I learned that you do not have to tell child components the form, the FormGroupDirective is available to children automatically.
See this library https://www.npmjs.com/package/ng-error-messages for show error messages based on validation rules:
<input placeholder="Texto:" formControlName="text">
<div errorMessage="text" alias="Super Texto" ></div>

How to add a contact form to a static web site?

I have a mostly "static" web site with no server-side code and just a little JavaScript. Now I would like to add a contact form. I do not care how I get the contact form data (so just writing this data to a text file in the server will be ok).
What is the simplest solution for this problem? How do people usually handle this?
I believe I can add some server-side code (PHP or something) to handle the form (and write the form data to a file, for instance) but I would prefer a client-side solution.
Use an external tool, they are commonly referred to as "formmailer". You basically submit the form to their server, and they send the form contents via mail to you.
If you don't want that, you have to do something server-sided: Storing data on the server, without having a server side program that accepts the data from the client, is just not possible.
You could install CouchDB and interface that from Javascript :) Everyone could use that then, too :)
The most easy PHP script that stores POST data on your harddisk:
<?php file_put_contents('/path/to/file', serialize($_POST) . "\n", FILE_APPEND); ?>
You can use Google Drive and create form with required fields. and embed code (which will be iframe) in your static web page.
You will be able to get submitted data in spreadsheet.
You can use qontacto . it is a free contact form you can add to any website. it forwards you the messages.
I set up the fwdform service for this exact need.
Just two simple steps to get your form forwarded to your email.
1.Register
Make an HTTP POST request to register your email.
$ curl --data "email=<your_email>" https://fwdform.herokuapp.com/register
Token: 780a8c9b-dc2d-4258-83af-4deefe446dee
2. Set up your form
<form action="https://fwdform.herokuapp.com/user/<token>" method="post">
Email: <input type="text" name="name"><br>
Name: <input type="text" name="email"><br>
Message: <textarea name="message" cols="40" rows="5"></textarea>
<input type="submit" value="Send Message">
</form>
With a couple of extra seconds you can spin up your own instance on Heroku.

grails form redirect gives 404, but url mapping works

I feel like I've entered the Twilight Zone. I have a Grails form that redirects to a URL, but gives a 404. If I go directly to that exact URL, everything works fine (that is, the URL mappings are correct).
This is an example generated form tag:
<form action="/alm/contactRefresh/itemRefreshProcess/7070" method="post">
On submit, it redirects to:
http://localhost:8080/alm/contactRefresh/itemRefreshProcess/7070
But gives this error:
HTTP ERROR 404
Problem accessing /alm/contactRefresh/itemRefreshProcess/7070. Reason:
NOT_FOUND
Powered by Jetty://
But then if I just go directly to that same URL (by focusing the browser Location bar and pressing enter), the page renders just fine, though the form params are lost because it's just a GET now. I've also tried changing the form method to GET, and that doesn't work either (throws a 404).
I've done similar forms a zillion times before with no problems. I'm sure this is some stupid user error, but I seriously can't figure out what's wrong.
Thanks for any ideas!
So, I finally started ripping parts out of the form and found out that for some reason you can’t name a Grails checkbox starting with the word "action". It must be something related to the default params["action"] entry. Though my checkbox names were a concatenation of "action_" + an id.
Anyway, there was some kind pre-processing of the checkbox form params that was blowing up before making it to the controller, and somehow that translated to a 404 instead of an actual Exception.
Originally I had this:
<g:checkBox name="action_${serviceRefreshAction.id}" value="${true}" />
Which renders this:
<input type="hidden" name="_action_7196" /><input type="checkbox" name="action_7196" checked="checked" id="action_7196" />
I changed "action" to "myAction", like this:
<g:checkBox name="myAction_${serviceRefreshAction.id}" value="${true}" />
Which renders this:
<input type="hidden" name="_myAction_7206" /><input type="checkbox" name="myAction_7206" checked="checked" id="myAction_7206" />
And now everything works fine.
Five hours of my life down the drain.
But I guess I have to forgive Grails, for the all time it saves me on a daily basis normally. :o)

How to Update asp:Label after AJAX Callback

I'm using the ajaxtoolkit:Rating. It all works fine except I'm trying to write a value to an asp label on the changed event and can't get it to work. Here are the relevant lines of code:
page.aspx
<asp:LoginView ID="LoginView1" runat="server">
<LoggedInTemplate>
<td>
<ajaxtoolkit:Rating ID="YourRating" runat="server" BehaviorID="RatingBehavior1" CurrentRating="0"
MaxRating="10" StarCssClass="ratingStar" WaitingStarCssClass="savedRatingStar"
ReadOnly="false" FilledStarCssClass="filledRatingStar" EmptyStarCssClass="emptyRatingStar"
OnChanged="YourRating_Changed" />
</td>
<td>
(<asp:Label ID="YourRatingNumber" Text="" runat="server"></asp:Label>)
</td>
</LoggedInTemplate>
<AnonymousTemplate>
<td>
Login or Register to Rate
</td>
</AnonymousTemplate>
page.aspx.cs
protected void YourRating_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
{
((HtmlGenericControl)FindControl("MainContent_LoginView1_YourRatingNumber")).InnerHtml = e.Value;
}
What I'm trying to do is update my asp:label control named "YourRatingNumber" text to e.value. I've tried many ways. I realize the asp:label is rendered as a span tag but I can't seem to access that value either. How can do this?
Thanks ... Bob
AJAX is asynchronous, meaning that a page load does not occur. Changing the value of a label server-side during an AJAX operation causes nothing client side. You would need to signal the client to update the page. You should use javascript to do this. I do not think you can do this using Web Forms. If you use MVC, you can use their AJAX helpers to do this, but it would require rewriting the site.
I would suggest that you write some javascript to cause an AJAX event and have it update the label when it gets a response. I would also suggest reading http://w3schools.com/ajax/default.asp, it explains how to use javascript to create AJAX requests, but you would need to tweak it a little to work with asp.net.
Also note, you should include whether you are using Web Forms or MVC, although they are similar, they have different handling of AJAX.

SiteFinity 4.0: Trouble Accessing Postback Data in Custom User Control

I'm trying to get a highly customized hand built form into sitefinity 4.0 and my problem is that no matter what I do I can't access the form's postback data in the code behind. My form is a user control and I've added it in the way described here:
http://www.sitefinity.com/40/help/developer-manual/controls-adding-a-new-control.html
After struggling for several hours, I created a basic test form and I'm still not able to access the postback data. I've also tried adding EnableViewState="true" all over the place but the form data is still empty on postback. The exact same user control runs and posts data perfectly outside of sitefinity. I also tried other methods of accessing the postback data and I discovered that Request.Form does contain the data I need. I'd still love to access my form elements in the usual way though, so I don't have to do Request.Form for every control on the page and loop that way, which seems really hokey.
Here's the code for the basic form:
"BasicUserControl.ascx"
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="BasicUserControl.ascx.cs" Inherits="SitefinityWebApp.UserControls.Assessments.BasicUserControl" EnableViewState="true" %>
<div id="assessmentDiv" runat="server">
<asp:TextBox ID="TextBox1" runat="server" clientidmode="Static" enableviewstate="true"></asp:TextBox>
<asp:Literal ID="Literal1" runat="server" clientidmode="Static" enableviewstate="true"></asp:Literal>
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
"BasicUserControl.ascx.cs" Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SitefinityWebApp.UserControls.Assessments
{
public partial class BasicUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Literal1.Text = TextBox1.Text;
}
}
}
}
Again, if I add the control via the method described at the link above, I am able to successfully create a Sitefinity 4.0 CMS page, drag the control onto it, run the page, step into the code behind using the debugger, yet when VS2010 reaches the line below there is no form data being posted:
Literal1.Text = TextBox1.Text;
FYI: The reason why there is no form tag in my usercontrol.ascx code above is because I get an error when running the form thru sitefinity that only one server-side form tag can exist on a .net page (sitefinity injects it's own form tag).
Thanks in advance for your help!
Ben
Never mind - I figured it out. For some reason, data isn't available at the Page_Load stage of the .net page lifecycle in a sitefinity form submission (at least not via a custom user control). If I wait until the Page_PreRender stage to retrieve the data from the form on the page, it's all there.
My current prevailing theory is that Sitefinity 4.0 grabs the postback data when a form submits and hasn't finished monkeying around with it at the Page_Load stage, so you have to wait until the Page_PreRender stage before sitefinity has injected the data back into the page cycle.
I had the same issue you did and came to the same solution. Spent a bunch of time on it - wish this answer had been around then.
Try adding enableviewstate into masterpages. I had the same situation and solved with this.
Also checked "enable view state" when creating pages.
Hope this help.
`<%# Master Language="C#" AutoEventWireup="true" CodeFile="HomePageClubManavgat.master.cs" Inherits="App_Master_HomePageClubManavgat" EnableViewState="true" %>
<script type="text/C#" runat="server">
protected override void OnInit(EventArgs e)
{
this.Page.EnableViewState = true;
base.OnInit(e);
}
`