help me ! MVC and AJAX toolkit Editor in ASP.NET - ajax

I have view to use Ajax toolkit editor control.
View CreateProduct
<fieldset>
<legend>Product information</legend>
<table align="center">
<tr>
<td><label for="slogan">Slogan:</label></td>
<td><%= Html.TextBox("slogan")%></td>
</tr>
<tr>
<td><label for="content">Content :</label></td>
<td>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<cc1:Editor ID="content" runat="server" Height="300px" />
</td>
</tr>
</table>
</fieldset>
ProductController:
public ActionResult CreateProduct(string slogan, string content)
{
ProductDataContext data = new ProductDataContext();
PRODUCT p = new PRODUCT();
p.SLOGAN = slogan;
p.CONTENT = content;
data.AddProduct(p);
data.SubmitChanges();
return View();
}
When I added a product, just slogan was added, content was null.
I dont understand and how to repair it.
Help me, please!
Thanks so much!

It does not work this way. You are mixing ASP.NET WebForms with MVC. ID="content" only sets the server-side ID of the Editor control. Controller parameters however are mapped by form field names and in your case the name of the corresponding textarea is generated automatically. I'm not aware of any way you could normally change the name of a control rendered by ASP.NET. You can, however try the following:
<script type="text/javascript">
document.getElementById('<%= content.ClientID =>').name = 'content';
</script>
Put this at the bottom of your view. It might just work.
Keep in mind that even if it works, the above is a dirty hack. The right approach in an MVC project would be to initialize the Editor control using just client scripting. This is not always easy but doable. For reference, try looking at the source of this page:
http://www.asp.net/ajax/ajaxcontroltoolkit/samples/htmleditor/OtherSamples/ClientSide.htm

Related

reinitialize datatables with external form data (server-side django app)

I am working on a django web app, and successfully implemented the fantastic jQuery datatables to present my data with server-side processing. I don't have access to the original files (this is a project for my workplace, they don't have internet access and I'm home now), but it looks something like this:
template:
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "/user_table/"
} );
} );
</script>
<table id='example'>
<thead>
<th>name</th>
<th>state</th>
<th>email</th>
</thead>
<tbody>
<td colspan="3" class="dataTables_empty">Loading data from server</td>
</tbody>
</table>
server_side:
def main_view(request):
return render_to_response('index.html')
def datatables_view(request):
start = request.GET['iDisplayStart']
length = request.GET['iDisplayLength']
query = myUser.objects.all()
if request.GET.has_key('sSearch'):
# filtering...
query = query[start:start+length]
response = ["aaData": [(q.name, q.state, q.email) for q in query]]
# return serialized data
again, like I mentioned, I'm not having any trouble with this. The integration works fine. Even better than fine, really. I love it.
What I really need though, is little more complex filter than the default one that datatables comes with. There are very specific types of search relevent for my work that will be very useful. So I have a form that appears vertically above the table. Let's say it looks something like this:
<form>
<label for='name'>name:</label>
<input type='text' name='name'></input>
<label for'costumer'>costumer?</label>
<input type='checkbox' name='costumer'></input>
<select multiple="multiple">
<option id='regular'>regular</option>
<option id='new'>new</option>
</select>
<input type='submit' value='filter!'> </input>
</form>
I want that when a user clicks on the submit button it would send the form data and re-initialize the datatable with my costumized filtering. Then I want another button that would refresh and reload the datatable and cancel out any initial data it was sending (as if you refreshed the page, without actually).
I'm not very experienced with javascript, so simple solutions are the best, but any help would be very much appreciated.
I solved it! Finally...
I used the jquery-datatables-column-filter plugin. It's decent and simple to use, and they have an example on their site how to use an external form. It's true that I'm not actually filtering on specific columns, but since I'm using server-side it doesn't really matter.

Validating TextBox input for a list that is a property of an MVC3 ViewModel

I realize I'm a little late to the party, but... I'm working in my first MVC project, and have been able to get a handle on most of what needs to be done. Most of the project simply reads data and pumps the data into charts. However, I have one View whose model looks like this (the parent class properties are not important here):
public class Class1 : ParentClass
{
public List<ChildClass> ChildClassList{get;set;}
}
and the ChildClass looks like this:
public class ChildClass
{
public int Property1{get;set;}
public int Property2{get;set;}
public string Property3{get;set;}
public int? ID{get;set;}
[Editable(true)]
public decimal? Property4{get;set;}
}
Now, retreiving the data is not an issue. I can loop through the list, and create a table for editing like this:
<% foreach(var g in Model.ChildClassList){%>
<tr>
<td style="text-align: right;">
<%= Html.Label(g.Property3)%>
</td>
<td>
<%=Html.TextBox(Model.ParentProperty.ToString() + "_" + g.Property2, (g.Property4.HasValue ? g.Property4.Value.ToString("C") : "$0.00"))%>
</td>
</tr>
<% }%>
After cruising through this site for the past couple of days, it dawned on me that I can validate the input on the server-side, in the POST method (there is a "Save" button at the bottom of the form), but (a)how do I get the validation error message back to the user, (b)perform the validation client-side?.
I must mention also that this view uses the values in the list to create a portion of a chart, prior to being rendered as a table.
On the server-side in the [HttpPost] action, you can check the validity of the model like this:
[HttpPost]
public ActionResult Save(Class1 model)
{
if (!ModelState.IsValid)
return View(model);
// Code to save model.
}
You also need to update your View to show the errors:
<%= Html.ValidationSummary(false, "Please fix these errors.")
<% foreach(var g in Model.ChildClassList){%>
<tr>
<td style="text-align: right;">
<%= Html.Label(g.Property3)%>
</td>
<td>
<%=Html.TextBox(Model.ParentProperty.ToString() + "_" + g.Property2, (g.Property4.HasValue ? g.Property4.Value.ToString("C") : "$0.00"))%>
<%= Html.ValidationMessageFor(model => g.Property4)
</td>
</tr>
<% }%>
If you want to enable it client-side, you need to use unobstrusive client validation, which you can do by updating your web.config:
<configuration>
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
</configuration>
Also you need the following JS libraries:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js" type="text/javascript"></script>
<script src="//ajax.microsoft.com/ajax/jQuery.Validate/1.7/jQuery.Validate.min.js" type="text/javascript"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
On a side note, try and avoid loops to render out your View. It's unnecessary code soup, which can be avoided by the use of editor templates.

MVC3 Razor Partial view render does not include data- validation attributes

I have a farily straight forward form that renders personal data as a partial view in the center of the form. I can not get client side validation to work on this form.
I started chasing down the generate html and came up with the same model field rendered on a standard form and a partial view.
I noticed that the input elements are correctly populated on the first call, #html.partial, the following only happens when the partialview is reloaded via an ajax request.
First the header of my partial view, this is within a Ajax.BeginForm on the main page.
#model MvcMPAPool.ViewModels.EventRegistration
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function ()
{
$(".phoneMask").mask("(999) 999-9999");
});
</script>
#{
var nPhn = 0;
var dTotal = 0.0D;
var ajaxOpts = new AjaxOptions{ HttpMethod="Post", UpdateTargetId="idRegistrationSummary", OnSuccess="PostOnSuccess" };
Html.EnableClientValidation( true );
Html.EnableUnobtrusiveJavaScript( true );
}
Here is the razor markup from the partial view:
#Html.ValidationMessageFor(model=>Model.Player.Person.Addresses[0].PostalCode)
<table>
<tr>
<td style="width:200px;">City*</td>
<td>State</td>
<td>Zip/Postal Code</td>
</tr>
<tr>
<td>#Html.TextBoxFor(p=>Model.Player.Person.Addresses[0].CityName, new { style="width:200px;", maxlength=50 })</td>
<td>
#Html.DropDownListFor(p=> Model.Player.Person.Addresses[0].StateCode
, MPAUtils.GetStateList(Model.Player.Person.Addresses[0].StateCode))</td>
<td>
<div class="editor-field">
#Html.TextBoxFor(p=>Model.Player.Person.Addresses[0].PostalCode, new { style="width:80px;", maxlength=10 })
</div>
</td>
</tr>
</table>
Here is the rendered field from the partial view:
<td>
<div class="editor-field">
<input id="Player_Person_Addresses_0__PostalCode" maxlength="10" name="Player.Person.Addresses[0].PostalCode" style="width:80px;" type="text" value="" />
</div>
</td>
Here is the same model field rendered in a standard view:
<div class="editor-field">
<input data-val="true" data-val-length="The field Postal/Zip Code must be a string with a maximum length of 10." data-val-length-max="10" data-val-required="Postal or Zip code must be provided!" id="Person_Addresses_0__PostalCode" maxlength="10" name="Person.Addresses[0].PostalCode" title="Postal/Zip Code is required" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Person.Addresses[0].PostalCode" data-valmsg-replace="true"></span>
</div>
Notice that the partial view rendering has no data-val-xxx attributes on the input element.
Is this correct? I do not see how the client side validation could work without these attributes, or am I missing something basic here?
In order to create the unobtrusive validation attributes, a FormContext must exist. Add the following at the top of your partial view:
if (this.ViewContext.FormContext == null)
{
this.ViewContext.FormContext = new FormContext();
}
If you want the data validation tags to be there, you need to be in a FormContext. Hence, if you're dynamically generating parts of your form, you need to include the following line in your partial view:
#{ if(ViewContext.FormContext == null) {ViewContext.FormContext = new FormContext(); }}
You then need to make sure you dynamically rebind your unobtrusive validation each time you add/remove items:
$("#form").removeData("validator");
$("#form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#form");

ASP.Net MVC 3 Unobtrusive validation not working on Partial View

I've setup a partial view which houses its own form tag, like so:
<tr>
#using (Html.BeginForm("Create"))
{
<td>
#Html.TextBoxFor(model => model.Date)
#Html.ValidationMessageFor(model => model.Date)
</td>
<td>
#Html.TextBoxFor(model => model.Amount)
#Html.ValidationMessageFor(model => model.Amount)
</td>
<td>
#Html.TextBoxFor(model => model.Tags)
#Html.ValidationMessageFor(model => model.Tags)
</td>
<td>
#Html.EnumDropDownListFor(model => model.Type)
</td>
<td>
<input type="submit" value="Add" />
#Html.ValidationSummary(true)
</td>
}
</tr>
I render it on a page using #Html.Action("Create") (It's part of a table, hence the <tr> tags.
For some odd reason my clientside validation isn't working, and I first see the errors upon posting.
Is there something special about partial views and clientside validation ?
I have included the following scripts:
<script src="/Scripts/jquery.1.5.1.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
EDIT
I just tried tossing this script onto the page:
jQuery('form').submit(function ()
{
alert(jQuery(this).valid());
});
It alerts 'true', so the clientside validation script is definately there, and for some reason it's not checking the fields in question :-/
EDIT 2
I've uploaded the entire source code for the page (the HTML + JS) to pastebin: http://pastebin.com/GvqLW495
Edit:
I just realized, looking at your code, that you're using jQuery 1.5.1 with the (I'm assuming) .NET provided jQuery.validate. Unfortunately, those two do not work together yet. You'll have to head to here to grab a version that works with the latest jQuery (you'll need to use 1.4.4). If that doesn't work, I would still recommend checking out the solution below.
I had a similar problem (although I'm not sure it's the exact same problem). I wrote about the solution in this blog post. Unfortunately, I can't be sure you're having the same exact problem, but it's worth a shot.
Basically, it boiled down to the fact that I had to call this line after loading my PartialViews (although I was loading them via AJAX which is what I think caused the problem):
$.validator.unobtrusive.parse($("#validation"));
See the blog post for more detail. Hopefully it helps you out.
I finally found out what's causing it to fail, it's the fact that my partial view is inside a html table...
<table>
<tr>
<th>
Date
</th>
<th>
Amount
</th>
<th>
Tags
</th>
<th>
Type
</th>
<th>
</th>
</tr>
#Html.Action("Create")
</table>
This doesn't work, however if I move the #Html.Action outside the table tag, it works just fine.
I think that the root of your problem wat the use of illegal html syntax:
<tr> tag can only contain <td> tags.
In most cases structure like your's won't be rendered correcty in browsers, especiallywhen loaded asynchronously.

requesting parameters from jsp

I have some problems with taking a parameters from jsp page, when method POST occurs.
My JSP page looks like this:
....
<table border="1">
<tr>
<th>name</th>
<th>check</th>
</tr>
<c:forEach items="${things}" var="pair">
<tr>
<td>${things.name}</td>
<td><INPUT TYPE="CHECKBOX" NAME=items VALUE=${things.id} ></td>
</tr>
</c:forEach>
</table>
<form method="post">
<input type="submit" value="Check all" />
</form>
So, I want to take all checked "things" in table. In controller class I something like this (written in Spring):
....
#RequestMapping(method = RequestMethod.POST)
public String sumbitForm(#RequestParam("items") String[] items){
if(items!= null){
for(String item: items){
....
}
}
return "redirect:myPage";
}
But my app don't want to work with such RequesParam. It doesn't put the values of items parameter to it. (this method I took here http://www.go4expert.com/forums/showthread.php?t=4542)
Also I tried using #ModelAttribute instead of #RequesParam. When I'm using it, my app don't give a errors, but it also couldn't correctly put the "items" to this parameter.
Any ideas?
P.S. May be you know more better method of taking list of parameters from JSP page for using their values (like taking checked items)?
Your table is outside of the <form></form> so when submitting, it doesnt send anything.

Resources