i want to stop form submit by client side validation done by models attribute. i have done every possibilities but mot success.. please look this code:
My Model is
[Key]
public int User_ID { get; set; }
[Required(ErrorMessage = "* Please Enter FirstName")]
public string User_FN { get; set; }
[Required(ErrorMessage = "* Please Enter MiddleName")]
public string User_MN { get; set; }
[Required(ErrorMessage = "* Please Enter LastName")]
public string User_LN { get; set; }
[Required(ErrorMessage = "* Please Enter LoginID")]
public string User_Login { get; set; }
[Required(ErrorMessage = "* Please Enter PassWord")]
public string User_Password { get; set; }
[Required(ErrorMessage = "* Please Select a Valid Role")]
public int User_Role_ID { get; set; }
[Required(ErrorMessage = "* Please Select any one Table")]
public List<int> Table_ID { get; set; }
[Required]
public List<bool> P_Add { get; set; }
[Required]
public List<bool> P_Edit { get; set; }
[Required]
public List<bool> P_Delete { get; set; }
and i added this reference jquery files
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
and set these keys to
<appSettings>
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
all the setting done but page still submitted...Please suggest me
You need to load validate.js before validate.unobtrusive.min.js
Related
Here's the problem. I have a [Range] attribute above the SalesCenterId property of my ViewModel. On my view side I have dropdown list with a default option "---Select---" and some Sales Centers with different Id-s. For example, if I set the Range between 0 and 1, then when selecting a sales center with Id = 2, my custom error message works. But when i select the default option "---Select---" (id = 0 , range between 1 and 1000) then the default error message is displayed: "The value '---Select---' is not valid for SalesCenterId." Why is this? I've checked through debugging and saw that when choosing "---Select---" Id = 0.
I'm using MVC core 2.2
ViewModel:
public class OrderViewModel
{
[Required(ErrorMessage = "*The Last Name field is required.")]
public string LastName { get; set; }
[Required(ErrorMessage = "*The First Name field is required.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "*The Middle Name field is required.")]
public string MiddleName { get; set; }
[Required(ErrorMessage = "*The Pin field is required.")]
public string Pin { get; set; }
[Required(ErrorMessage = "*The Phone field is required.")]
public string Phone { get; set; }
[Required(ErrorMessage = "*The Email field is required.")]
public string Email { get; set; }
[Required(ErrorMessage = "*The Serial Number field is required.")]
public string SerialNumber { get; set; }
[Range(1, 1000, ErrorMessage="jgsjfdngi")]
public int SalesCenterId { get; set; }
[Range(1, 999, ErrorMessage = "jgsjfdngi")]
public int OrderTimeId { get; set; }
[JsonIgnore]
[IgnoreDataMember]
public SalesCenter SalesCenter { get; set; }
public List<CartItem> Cart { get; set; }
public OrderTime OrderTime { get; set; }
public decimal TotalPrice { get; set; }
}
Validation message span:
<p><span asp-validation-for="SalesCenterId" class="error"></span></p>
Select list:
<td>
<select id="SCID" asp-for="SalesCenterId" asp-items="#ViewBag.SalesCenterId" class="input" style="width:200px; height:30px; padding:1.5%">
<option>---#Localizer["Select"]---</option>
</select><br />
</td>
I expect the output to be "jgsjfdngi", but the actual output is "The value '---Select---' is not valid for SalesCenterId."
Have you used ModelState.IsValid in your controller??
Try this
if (ModelState.IsValid)
{
// your code
return View();
}
return View();
public class project
{
public int id { get; set; }
public string ProjectName { get; set; }
public string Description { get; set; }
public string Category { get; set; }
public int UserprojectId { get; set; }
public int? SponserId { get; set; }
public decimal Cost { get; set; }
public DateTime CreatedTime { get; set; }
public DateTime EstimateTime { get; set; }
}
public class projectDB : DbContext
{
public DbSet<project> projects { get; set; }
}
and this model
public class sponser
{
public int id { get; set; }
public string FirstName { get; set; }
public string lastName { get; set; }
public string CompanyName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public DateTime DateRegister { get; set; }
public String CompanyPhone { get; set; }
public string CellPhone { get; set; }
public string Email { get; set; }
public bool EmailConfirmation { get; set; }
public string Country { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public String Address { get; set; }
}
public class sponserDB : DbContext
{
public DbSet<sponser> sponsers { get; set; }
}
and in my web confige file
i add this this name
<add name="SponseringDB"
connectionString="Data Source=(localdb)\v11.0;Initial Catalog=sponseringDB;Integrated Security=True"
providerName="System.Data.SqlServerCe.4.0"
/>
When run this and create some Record for me it made two database first sponseringDb and second is projectDb I want to use one database.
Need suggestions on achieving this.
You've got two classes inherit by DbContext and that is the reason why 2 database are created, if you want to have just one databe ie: projectDB
change you projectDB class to
public class projectDB : DbContext
{
public projectDB () : base("projectDBConnectionString") //<- name of your connection string
{
}
public DbSet<project> projects { get; set; }
public DbSet<sponser> sponsers { get; set; }
}
and in your web config add connection string named 'projectDBConnectionString' ie:
<add name="projectDBConnectionString"
connectionString="Data Source=(localdb)\v11.0;Initial Catalog=sponseringDB;Integrated Security=True"
providerName="System.Data.SqlServerCe.4.0"
/>
and now your can rid off connection string 'SponseringDB' from web.config and delete class 'sponserDB'
Hope that will help
This is my code in which i used the drop down in my kendo grid single column and i have used Editor template , foreign key column but none of these work according to my choice...
that is my code check
-Editor template column
columns.Bound(p => p.Table_ID).ClientTemplate("#= Table_ID #" +
"<input type='hidden' name='PrevilegeViewModels[#= index(data)#].Table_ID' value='#= Table_ID #' />"
).EditorTemplateName("Table").Title("Table").Width(300);
foreign key column
columns.ForeignKey(p => p.Table_ID, (System.Collections.IEnumerable)ViewBag.Table, "ID", "Name").ClientTemplate("#= Table_ID #" +
"<input type='hidden' name='PrevilegeViewModels[#= index(data)#].Table_ID' value='#= Table_ID #' />"
);
that is my Editor column in which i initilized a kendo dropdown Please
#using System.Collections
#model System.Int32
#(Html.Kendo().DropDownList()
.BindTo((IEnumerable)ViewBag.Table)
.OptionLabel("------------- Select Table -------------- ")
.DataValueField("ID")
.DataTextField("Name")
)
And these are two models
public class UserViewModel
{
[Key]
public int User_ID { get; set; }
[Required(ErrorMessage = "* Please Enter First Name")]
public string User_FN { get; set; }
[Required(ErrorMessage = "* Please Enter Middle Name")]
public string User_MN { get; set; }
[Required(ErrorMessage = "* Please Enter Last Name")]
public string User_LN { get; set; }
[Required(ErrorMessage = "* Please Enter Login ID")]
public string User_Login { get; set; }
[Required(ErrorMessage = "* Please Enter PassWord")]
public string User_Password { get; set; }
[Required(ErrorMessage = "* Please Select a Valid Role")]
public int User_Role_ID { get; set; }
public IEnumerable<PrevilegeViewModel> PrevilegeViewModels { get; set; }
}
and another
public class PrevilegeViewModel
{
[Key]
public int Previleges_ID { get; set; }
[Required]
[Range(1,UInt32.MaxValue)]
public int Table_ID { get; set; }
[Required]
public bool P_Add { get; set; }
[Required]
public bool P_Edit { get; set; }
[Required]
public bool P_Delete { get; set; }
}
and when i didn't select any value grid show 0 but i provide the range b/w 1 to int32.max...
Please check the code..
Okay so I have a MVC project that auto generates an AccountController AcountModel and the associated views.
I created a database with 3 tables using the model first approach, and generated all the controllers/views for all the CRUD operations.
The database contains a user table with a user id, email and password.
How can I use this user table with the auto generated AccountController for user login and registration?
I will show you registration process only , refering which you can build your login/registration with custom database.
Models:
You will add your custommodel to the AccountModels.cs, So it will have following details:
public class ChangePasswordModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[System.Web.Mvc.Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class LogOnModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[System.Web.Mvc.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class userDetailModel
{
[Key]
public Guid UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string city { get; set; }
public string ConfirmPassword { get; set; }
public string comapny { get; set; }
public int zip { get; set; }
}
Context:
You will add custom context to the Models as below:
public class userDetailsDBContext: DbContext
{
public DbSet<userDetailModel> details { get; set; }
}
Controller:
Now we will modify our AccountController for registration as below:
public class AccountController : Controller
{
private userDetailsDBContext db = new userDetailsDBContext();
// POST: /Account/Register
[HttpPost]
public ActionResult Register(userDetailModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
var newuser = Membership.GetUser(model.UserName);
model.UserId =(Guid)newuser.ProviderUserKey;
db.details.Add(model);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
}
EDIT web.config:
Finally, you will have to add the new context to the connectionstrings as below:
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MembershipSample-20121105163515;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MembershipSample-20121105163515.mdf" />
<add name="userDetailsDBContext" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MembershipSample-20121105163515;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MembershipSample-20121105163515.mdf" />
</connectionStrings>
You can change the database name to whatever you want and put it as your convenience but put the path here correctly.
Hope you have got the idea now...
I think waht you need is to create custom membership provider. This code project article will give you aplace to start.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a wcf service with the following web.config in the server.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="myconnection" connectionString="myconnectionstr"/>
</connectionStrings>
<system.serviceModel>
<services>
<service behaviorConfiguration="PSWebServis.PServisBehavior" name="PSWebServis.PServis">
<endpoint address="" binding="wsHttpBinding" contract="PSWebServis.IPServis" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="PSWebServis.PServisBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
and this is related part in web.config in client.
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IPServis" />
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://sunucu:8000/PServis.svc" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IPServis" contract="PSWebServis.IPServis"
name="WSHttpBinding_IPServis">
<identity>
<servicePrincipalName value="host/SUNUCU" />
</identity>
</endpoint>
</client>
Here is a part of my interface in the service
[ServiceContract]
public interface IPServis
{
[OperationContract]
string InsertMusteri(MusterilerModel musteri);
}
and related part in service class.
public class PServis : IPServis
{
public string InsertMusteri(MusterilerModel musteri)
{
if (musteri != null)
{
DataTable dtSonuc = new DataTable();
SqlCommand command = new SqlCommand("InsertMusteriModel", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#musteriTablo", musteri.KayitTablosu);
command.Parameters.AddWithValue("#telefonTablo", musteri.TelefonKayit);
command.Parameters.AddWithValue("#adresTablo", musteri.AdresKayit);
connection.Open();
command.ExecuteNonQuery();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(dtSonuc);
connection.Close();
return dtSonuc.Rows[0]["IslemDurum"].ToString();
}
return "Başarısız";
}
}
My MusterilerModel class:
[DataContract]
public class MusterilerModel
{
[DataMember(Order=0)]
public int MusteriID { set; get; }
[DataMember(Order = 1)]
public string Ad { set; get; }
[DataMember(Order = 2)]
public string Soyad { set; get; }
[DataMember(Order=3)]
public string KullaniciAdi { set; get; }
[DataMember(Order = 4)]
public string Email { set; get; }
[DataMember(Order = 5)]
public DateTime DogumTarihi { set; get; }
[DataMember(Order=6)]
public string GrupAdi { set; get; }
[DataMember(Order=7)]
public int Renk { set; get; }
[DataMember(Order=8)]
public decimal Bakiye { set; get; }
[DataMember(Order=9)]
public string Adres { set; get; }
[DataMember(Order=10)]
public string AdresAciklamasi { set; get; }
[DataMember(Order=11)]
public string Firma { set; get; }
[DataMember(Order=12)]
public string VergiDairesi { set; get; }
[DataMember(Order=13)]
public string VergiNo { set; get; }
[DataMember(Order=14)]
public int BayiID { set; get; }
[DataMember(Order=15)]
public string Il { set; get; }
[DataMember(Order = 16)]
public string Ilce { set; get; }
[DataMember(Order = 17)]
public decimal YemekPara { get; set; }
[DataMember(Order=18)]
public string Sifre { set; get; }
[DataMember(Order=19)]
public int GrupID { set; get; }
[DataMember(Order=20)]
public string BayiAdi { set; get; }
[DataMember(Order=21)]
public int SehirID { set; get; }
[DataMember(Order=22)]
public int IlceID { set; get; }
[DataMember(Order=23)]
public DateTime EvlilikYilDonumu { set; get; }
[DataMember(Order=24)]
public DateTime KayitTarihi { set; get; }
[DataMember(Order=25)]
public string KayitEdenPersonel { set; get; }
[DataMember(Order=26)]
public int KayitEdenPersonelID { set; get; }
[DataMember(Order=27)]
public bool AktifMi { set; get; }
[DataMember(Order=28)]
public string Aciklama { set; get; }
[DataMember(Order=29)]
public string OzelKod { set; get; }
[DataMember(Order=30)]
public int SatisID { set; get; }
[DataMember(Order=31)]
public DataTable KayitTablosu { set; get; }
[DataMember(Order=32)]
public DataTable TelefonKayit { set; get; }
[DataMember(Order=33)]
public DataTable AdresKayit { set; get; }
}
When i try to use InsertMusteri method, there are 2 records in the database. As you see, i put my information into datatable and send it to the service. I checked, if datatable has more than 1 value but that was not the problem. I don't know where is the problem.
Comment this line
command.ExecuteNonQuery();
And check if it's work properly.
I think "Fill" command executs your command.