Can I use the MVC 2 DataAnnotations to specify a minimum length for a string field?
Has anyone done this or have they created custom attributes and if so do you mind sharing the source?
This is my Update Json method..
public JsonResult Update(StudentInfo e)
{
var cache = CacheFactory.GetCacheManager();
var Status= false;
for (int i = 0; i <= cache.Count; i++)
{
var x = (StudentInfo )cache.GetData("a" + i);
if (x != null)
{
Status= common.UpdateStudent(e.Student);
}
}
return Json(Status);
}
this is my veiw..
<% using (Html.BeginForm("Update", "home", FormMethod.Post))
{ %>
<%= Html.ValidationSummary(true)%>
my scripts..
<script type="text/javascript">
$(document).ready(function() {
$('#btnSelectAll').click(function() {
$('#btnSelect').click(function() {
$('#input[type=checkbox]').attr('checked', 'checked');
});
function validate_excpt(formData, jqForm, options) {
var form = jqForm[0];
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
if (responseText[0].substring(0, 16) != "System.Exception") {
$('#error-msg- span:last').html('<strong>Update successful.</strong>');
} else {
$('#error-msg- span:last').html('<strong>Update failed.</strong> ' + responseText[0].substring(0, 48));
}
$('#error-msg-').removeClass('hide');
$('#gui-stat-').html(responseText[1]);
}
// post-submit callback
$('#exc-').ajaxForm({
target: '#error-msg-',
beforeSubmit: validate_excpt,
success: showResponse,
dataType: 'json'
});
$('.button').button();
});
$('.button').button();
$("input[id^='exc-flwup-']").datepicker({
duration: '',
showTime: true,
constrainInput: true,
stepMinutes: 30,
stepHours: 1,
altTimeField: '',
time24h: true,
minDate: 0
});
$('#ui-timepicker-div').bgiframe();
});
</script>
I am getting popupmessage when Jsonresult Update method has done..but I am seeing that user is updating perfectly..
popup window saying something like you have choosed to open if I open that I am getting string as True in the file..
is that above code I am doing something wrong?
This is driving me crazy, similar to this. If I use a standard form and no javascript the controller correctly binds the datetime. However when I'm posting from a form it always binds as null:
"MyObject.Name": "Test name",
"MyObject.Date": "5/1/2001"
I've tried a couple of variations, 5-1-2001, etc. but cannot seem to get it to take. I can confirm that it is being passed to the server as it shows up in the Request.Form string. My culture is Gregorian and I've set:
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
In Application_BeginRequest(). What gives?
I'm trying to follow the tutorial found here to implement a service layer in my MVC application. What I can't figure out is how to wire it all up.
here's what I have so far.
IUserRepository.vb
Namespace Data
Public Interface IUserRepository
Sub AddUser(ByVal openid As String)
Sub UpdateUser(ByVal id As Integer, ByVal about As String, ByVal birthdate As DateTime, ByVal openid As String, ByVal regionid As Integer, ByVal username As String, ByVal website As String)
Sub UpdateUserReputation(ByVal id As Integer, ByVal AmountOfReputation As Integer)
Sub DeleteUser(ByVal id As Integer)
Function GetAllUsers() As IList(Of User)
Function GetUserByID(ByVal id As Integer) As User
Function GetUserByOpenID(ByVal openid As String) As User
End Interface
End Namespace
UserRepository.vb
Namespace Data
Public Class UserRepository : Implements IUserRepository
Private dc As DataDataContext
Public Sub New()
dc = New DataDataContext
End Sub
#Region "IUserRepository Members"
Public Sub AddUser(ByVal openid As String) Implements IUserRepository.AddUser
Dim user = New User
user.LastSeen = DateTime.Now
user.MemberSince = DateTime.Now
user.OpenID = openid
user.Reputation = 0
user.UserName = String.Empty
dc.Users.InsertOnSubmit(user)
dc.SubmitChanges()
End Sub
Public Sub UpdateUser(ByVal id As Integer, ByVal about As String, ByVal birthdate As Date, ByVal openid As String, ByVal regionid As Integer, ByVal username As String, ByVal website As String) Implements IUserRepository.UpdateUser
Dim user = (From u In dc.Users
Where u.ID = id
Select u).Single
user.About = about
user.BirthDate = birthdate
user.LastSeen = DateTime.Now
user.OpenID = openid
user.RegionID = regionid
user.UserName = username
user.WebSite = website
dc.SubmitChanges()
End Sub
Public Sub UpdateUserReputation(ByVal id As Integer, ByVal AmountOfReputation As Integer) Implements IUserRepository.UpdateUserReputation
Dim user = (From u In dc.Users
Where u.ID = id
Select u).FirstOrDefault
''# Simply take the current reputation from the select statement
''# and add the proper "AmountOfReputation"
user.Reputation = user.Reputation + AmountOfReputation
dc.SubmitChanges()
End Sub
Public Sub DeleteUser(ByVal id As Integer) Implements IUserRepository.DeleteUser
Dim user = (From u In dc.Users
Where u.ID = id
Select u).FirstOrDefault
dc.Users.DeleteOnSubmit(user)
dc.SubmitChanges()
End Sub
Public Function GetAllUsers() As System.Collections.Generic.IList(Of User) Implements IUserRepository.GetAllUsers
Dim users = From u In dc.Users
Select u
Return users.ToList
End Function
Public Function GetUserByID(ByVal id As Integer) As User Implements IUserRepository.GetUserByID
Dim user = (From u In dc.Users
Where u.ID = id
Select u).FirstOrDefault
Return user
End Function
Public Function GetUserByOpenID(ByVal openid As String) As User Implements IUserRepository.GetUserByOpenID
Dim user = (From u In dc.Users
Where u.OpenID = openid
Select u).FirstOrDefault
Return user
End Function
#End Region
End Class
End Namespace
IUserService.vb
Namespace Data
Interface IUserService
End Interface
End Namespace
UserService.vb
Namespace Data
Public Class UserService : Implements IUserService
Private _ValidationDictionary As IValidationDictionary
Private _repository As IUserRepository
Public Sub New(ByVal validationDictionary As IValidationDictionary, ByVal repository As IUserRepository)
_ValidationDictionary = validationDictionary
_repository = repository
End Sub
Protected Function ValidateUser(ByVal UserToValidate As User) As Boolean
Dim isValid As Boolean = True
If UserToValidate.OpenID.Trim().Length = 0 Then
_ValidationDictionary.AddError("OpenID", "OpenID is Required")
isValid = False
End If
If UserToValidate.MemberSince = Nothing Then
_ValidationDictionary.AddError("MemberSince", "MemberSince is Required")
isValid = False
End If
If UserToValidate.LastSeen = Nothing Then
_ValidationDictionary.AddError("LastSeen", "LastSeen is Required")
isValid = False
End If
If UserToValidate.Reputation = Nothing Then
_ValidationDictionary.AddError("Reputation", "Reputation is Required")
isValid = False
End If
Return isValid
End Function
End Class
End Namespace
I have also wired up the IValidationDictionary.vb and the ModelStateWrapper.vb as described in the article above.
What I'm having a problem with is actually implementing it in my controller. My controller looks something like this.
Public Class UsersController : Inherits BaseController
Private UserService As Data.IUserService
Public Sub New()
UserService = New Data.UserService(New Data.ModelStateWrapper(Me.ModelState), New Data.UserRepository)
End Sub
Public Sub New(ByVal service As Data.IUserService)
UserService = service
End Sub
....
End Class
however on the line that says Public Sub New(ByVal service As Data.IUserService) I'm getting an error
'service' cannot expose type 'Data.IUserService' outside the project through class 'UsersController'
So my question is TWO PARTS
How can I properly implement a Service Layer in my application using the concepts from that article?
Should there be any content within my IUserService.vb?
Hi all,
I'm building a website at the moment, I've some html fragment that is being stored into the database, I've been reading around that inserting HTML at runtime poses security risks by using the InnerHTML property of any html tag with runat server on it.
So, my question is there any alternative way to safely display the html code and won't pose security risks and is it best to assume any textboxes on any given page is dangerous and process the text in the textboxes with Server.HtmlEncode before I store it to database?
Cheers
I have a form that I want to postback to some other server on button click . I am using onpostbackurl ...Its posting the form to other server but text field input is not getting into other server. If I remove enctype="multipart.. it seems to be working fine...but the thing is I am doing all this in sharepoint and
<formid="aspnetform" enctype="multipart/datapart"...is getting added on its own.....
in my control I am giving text field and button only .....Any idea how to achieve this...?
Hi There
I need to render a partial view to a string within a controller action. I have the following sample code, but the ControllerContext.ParentActionViewContext does not seem to exist in mvc 1.0
// Get the IView of the PartialView object.
var view = PartialView("MyPartialView").View;
// Initialize a StringWriter for rendering the output.
var writer = new StringWriter();
// Do the actual rendering.
view.Render(ControllerContext.ParentActionViewContext, writer);
Any tips greatly appreciated.
I'm overriding the onrowcreated to add sort images to the header row of a gridview. This works, but actually adding a sortexpression doesn't. What I want to do is set the images as imagebuttons and set their commandarguments to the sort expression of the column they are sorting for.
I would assume I could get the cell and from it's index get the gridviewcolumn. Then, I could just get the sortexpression of the gridview column, but this does not work. The columns are null. OnRowCreated Code snippet below:
//if this is the header row, we add sort images to each cell
if (row.RowType == DataControlRowType.Header)
{
//iterate through the cells
for (int i = 0; i < row.Cells.Count; i++)
{
//if the column is sortable and visible
if (this.Columns[i].SortExpression != string.Empty && this.Columns[i].Visible)
{
string strSort = this.Columns[i].SortExpression;
}
}
}
Can we not get columns in OnRowCreated like this?
So, I'd like to implement my own custom authorization system in MVC2.
If I'd have to create a global class, where do I instantiate it?
Can HttpContext be extended with my own additions and where do I do that?
Should I use Authorization filters for rights validation or ActionFilters or do it within an action?
Can ActionFilter pass any data to the action itself?
Previously (in WebForms) I was using a Session object where I would put a serialized object containing essential user data (account id and a list of roles and rights) and I'd extend my own Page class.
in Ms-Ajax
suppose iam downloading 3 files , no dependencies have been defined b/w them
Sys.loadScripts(['file1.js',file2.js',file3.js']);
a in which order these files will be loaded??
b in which order these files will be made available to requesting page??
public void DisplayThickBox(Page page, int width, int height)
{
string script = "<script type='text/javascript'>";
script += "$(document).ready(function(){";
script += "tb.show('null', 'auto-insurance-redirect.aspx?keepThis=true&TB_iframe=true&height=" + height.ToString() + "&width=" + width.ToString() + "',null);";
script += "});";
script +="</script>";
ScriptManager.RegisterStartupScript(page, page.GetType(), "", script, true);
}
^^^Method to display the thickbox...^^^
DisplayThickBox(this, 518, 321);
^^^Call to method in the click event of the button that fires it...^^^
Page is just refreshing and the thickbox is never displayed. I'm trying to call the javascript manually since im doing some other stuff before i display the thickbox in the code behind...
I have a User Control that contains a System.Web.UI.WebControls.FileUpload control as well as a button to 'Submit'.
When the button is clicked code similar to the following is executed:
If FileUploadControl.HasFile Then
'Save the file and do some other stuff
End If
This code works just fine with Windows XP. However, if I run it from a Windows 7 64-bit machine using IE8 32-bit the HasFile property always returns false and nothing is saved?!
Any suggestions/ideas would be greatly appreciated.
hi, i have following selectlist for dropdownbox in aspnet mvc.
This is the editEmployee Action controller, so while edit page is displayed i want to display a selectvalue in dropdownbox,since "SelectList" takes 3 parameters one for value,one for text and other is for selected value, here i'm not getting what should i pass in 3rd parameter, coz its asking an object for selected value.
ViewData["DepartmentList"] = new SelectList(DepartmentRepository.GetDepartmentsBySchoolIdInList(ViewData["schoolId"].ToString()),"DepartmentId","DepartmentTitle");
here is the view
=Html.DropDownList("DepartmentList")
Im trying to create a custom version of the RequiredAttribute to replace the built in one and I've got it working for properties that have strings values, but with properties that are DateTime or integer for example, the default RequiredAttribute seems to be applied automatically (IF the property is not nullable!)
My problem is that i want to be able to specify a DateTime property as required using my custom required validator which gets the error message from a resources file (I don't want to have to tell the RequiredAttribute the type of the resource file and the key every time i apply it. That is why I'm making a custom one.)
How can i prevent the framework from applying the required attribute to properties of type DateTime and int etc without changing them to nullable.
Thanks
I'm starting a web application that contains the following projects:
Booking.Web
Booking.Services
Booking.DataObjects
Booking.Data
I'm using the repository pattern in my data project only. All services will be the same, no matter what happens. However, if a customer wants to use Access, it will use a different data repository than if the customer wants to use SQL Server.
I have StructureMap, and want to be able to do the following:
Web project is unaffected. It's a web forms application that will only know about the services project and the dataobjects project.
When a service is called, it will use StructureMap (by looking up the bootstrapper.cs file) to see which data repository to use.
An example of a services class is the error logging class:
public class ErrorLog : IErrorLog
{
ILogging logger;
public ErrorLog()
{
}
public ErrorLog(ILogging logger)
{
this.logger = logger;
}
public void AddToLog(string errorMessage)
{
try
{
AddToDatabaseLog(errorMessage);
}
catch (Exception ex)
{
AddToFileLog(ex.Message);
}
finally
{
AddToFileLog(errorMessage);
}
}
private void AddToDatabaseLog(string errorMessage)
{
ErrorObject error =
new ErrorObject
{
ErrorDateTime = DateTime.Now,
ErrorMessage = errorMessage
};
logger.Insert(error);
}
private void AddToFileLog(string errorMessage)
{
// TODO: Take this value from the web.config instead of hard coding it
TextWriter writer = new StreamWriter(@"E:\Work\Booking\Booking\Booking.Web\Logs\ErrorLog.txt", true);
writer.WriteLine(DateTime.Now.ToString() + " ---------- " + errorMessage);
writer.Close();
}
}
I want to be able to call this service from my web project, without defining which repository to use for the data access. My boostrapper.cs file in the services project is defined as:
public class Bootstrapper
{
public static void ConfigureStructureMap()
{
ObjectFactory.Initialize(x =>
{
x.AddRegistry(new ServiceRegistry());
}
);
}
public class ServiceRegistry : Registry
{
protected override void configure()
{
ForRequestedType<IErrorLog>().TheDefaultIsConcreteType<Booking.Services.Logging.ErrorLog>();
ForRequestedType<ILogging>().TheDefaultIsConcreteType<SqlServerLoggingProvider>();
}
}
}
What else do I need to get this to work? When I defined a test, the ILogger object was null.
Thanks,
I am implementing a very simple requirements management tool.
I want the URLs to look like this:
Shows home page for "Project One":
http://projectmanager/Project/Project%20One
Shows a list of requirements being worked on for "Project One"
http://projectmanager/Project/Project%20One/Requirements
Shows requirement 1 for "Project One"
http://projectmanager/Project/Project%20One/Requirement/1
How could I set up routes so that
http://projectmanager/Project/Project%20One
is handled by the project controller
http://projectmanager/Project/Project%20One/Requirements
and
http://projectmanager/Project/Project%20One/Requirements/1
is handled by the requirements controller.
Is it even possible?
there is one linkbtn , on click i have to display word document content inside any textBox which supports, i used simple textbox but am facing the formatting problem. and also it does not show image. there is any idea for problem in display word document content inside any textBox .
i dont know about richtextbox, can i get any help, please send me desired code to [email protected]
The sample page for the MaskedEdit says "Tip: Type 'A' or 'P' to switch AM/PM". Are these keys hardcoded? Does the control automatically change itself for cultures that use 12-hour designators that don't start with A or P? Or is just broken for those?
example:
Arabic (Saudi Arabia) - AM: ?
Arabic (Saudi Arabia) - PM: ?
Chinese (Taiwan) - AM: ??
Chinese (Taiwan) - PM: ??
Greek (Greece) - AM: pµ
Greek (Greece) - PM: µµ
Korean (Korea) - AM: ??
Korean (Korea) - PM: ??
Albanian (Albania) - AM: PD
Albanian (Albania) - PM: MD
Persian (Iran) - AM: ?.?
Persian (Iran) - PM: ?.?
Vietnamese (Vietnam) - AM: SA
Vietnamese (Vietnam) - PM: CH
Afrikaans (South Africa) - PM: nm
Punjabi (India) - AM: ?????
Punjabi (India) - PM: ???
Syriac (Syria) - AM: ?.?
Syriac (Syria) - PM: ?.?
If this control doesn't handle this situation, does anyone know of a control that does?
I'm using Web Developer 2010. I just created a resource file lang.resx with different values in english. Then I created a lang.FR-fr.resx with French equivalents. However after tryingto compile, I get
Error 131 Task could not find "AL.exe" using the SdkToolsPath "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\" or the registry key "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A". Make sure the SdkToolsPath is set and the tool exists in the correct processor specific location under the SdkToolsPath and that the Microsoft Windows SDK is installed
This is so weird! If I remove FR-fr part, it will work, but there will be no translation of course.
I went to that directory and found out that I don't have al.exe there. I managed to find it in .NET 2 folder, but after copying it didn't help. It throws an exception. I tried to reinstall .NET 4, to install Windows SDK, and it still doesn't work.
Maybe I can somehow get this al.exe file?
I have an aspx page that is supposed to reference a code-behind variable but I am receiving an error of "The name [variable] does not exist in the current context"
Here is the aspx code
<%@ Control Language="C#" AutoEventWireup="true" Inherits="IPAM.Website.Controls.controls_event_header" Codebehind="event_header.ascx.cs" %>
<%# strEventLink %>
<h3><%# strEventDate %></h3>
<%# strLinks %>
Here is part of the aspx.cs code declaring those variables:
public string strEventLink = "";
public string strEventDate;
public string strLinks = "";
Here is the part of the aspx.cs code where it sets those variables:
strEventLink = "<h2>" + parent.Name + "</h2>";
strLinks += "<p><font size=\"+1\"><a href=\"" + Page.ResolveUrl("~" + strScheduleLink) + "\"><b>" + strScheduleLinkText + "</b></a></font></p>\n";
strEventDate = ei.DateSpan;
Please help me with this problem
I have a page that performs a long-running task (10 to 15 seconds) in the page_load method.
I have client-side javascript code that will display a decent "page loading" animated gif to the user.
I am able to invoke the JavaScript method from the code-behind, to display the "page loading" animated gif, however, the long-running task is hanging up the UI such that the animated gif doesn't actually display until after the long-running task is complete, which is the exact opposite of what I want.
To test this out, in my page_load method I make a call to the JavaScript method to display the animated gif. Then, I use Thread.Sleep(10000). What happens is that the animated gif doesn't display until after Thread.Sleep is complete.
Obviously I am doing something incorrect.
Any advice would be appreciated.
Thanks.
Chris
I'm attempting to encode the encrypted id in the Url. Like this: http://www.calemadr.com/Membership/Welcome/9xCnCLIwzxzBuPEjqJFxC6XJdAZqQsIDqNrRUJoW6229IIeeL4eXl5n1cnYapg+N
However, it either doesn't encode correctly and I get slashes '/' in the encryption or I receive and error from IIS: The request filtering module is configured to deny a request that contains a double escape sequence.
I've tried different encodings, each fails:
HttpUtility.HtmlEncode
HttpUtility.UrlEncode
HttpUtility.UrlPathEncode
HttpUtility.UrlEncodeUnicode
Update
The problem was I when I encrypted a Guid and converted it to a base64 string it would contain unsafe url characters . Of course when I tried to navigate to a url containing unsafe characters IIS(7.5/ windows 7) would blow up. Url Encoding the base64 encrypted string would raise and error in IIS (The request filtering module is configured to deny a request that contains a double escape sequence.). I'm not sure how it detects double encoded strings but it did.
After trying the above methods to encode the base64 encrypted string. I decided to remove the base64 encoding. However this leaves the encrypted text as a byte[]. I tried UrlEncoding the byte[], it's one of the overloads hanging off the httpUtility.Encode method. Again, while it was URL encoded, IIS did not like it and served up a "page not found."
After digging around the net I came across a HexEncoding/Decoding class.
Applying the Hex Encoding to the encrypted bytes did the trick. The output is url safe. On the other side, I haven't had any problems with decoding and decrypting the hex strings.
Hi,
I am confused, wanted to confirm the below statement -
We can create multiple event handle method for the same event?
I think yes, beacuse it is overloading concept? right?
Please correct my understanding or advise.
Thanks.