How to find an item in my database? - asp.net-mvc

So i want to create a person and add it to my table if i dont have the same name already in my table. i have this code in my controller
hesaplamaEntities hsb = new hesaplamaEntities();
[HttpPost]
public ActionResult Create(MyTable p)
{
MyTable obj = hsb.MyTable.Find(p);
if (obj.propname == null)
{
hsb.MyTable.Add(p);
hsb.SaveChanges();
return RedirectToAction("Create", "Home");
}
else
{
return HttpNotFound();
}
and this is my View :
#using (Html.BeginForm("Create", "Home", FormMethod.Post, new { #class =
"form-horizontal", enctype = "multipart/form-data" }))
{
<div class="row">
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-12">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
#Html.TextBoxFor(m => m.propname, new { #class = "form-control" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="col-sm-2 control-label">kod</label>
<div class="col-sm-10">
#Html.TextAreaFor(m => m.propkod, new { #class = "form-control" })
</div>
</div>
</div>
</div>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-sm-9 col-sm-offset-3">
<div class="btn-toolbar pull-right">
<input type="submit" value="save" class="btn btn-primary" />
</div>
</div>
</div>
</div>
}
and this is my Model :
public partial class MyTable
{
public int ID { get; set; }
public string propkod { get; set; }
public string propname { get; set; }
}
i am having this error when i am trying to add person :
he specified parameter type 'WebApplication7.Models.MyTable' is not valid. Only scalar types, such as System.Int32, System.Decimal, System.DateTime, and System.Guid, are supported.
and its showing me the error in this line : HesapTemel obj = hsb.HesapTemels.Find(p);
what is the probleme exactly ?

Related

How to use SweetAlert before return RedirectToAction by Form Post?

Model
public class Company{
[StringLength(30)]
public string Name{ get; set; }
[StringLength(15)]
public string RegisterNo { get; set; }
}
View
<form id="form" method="post" action="/Controller/Save" style="font-size:13px;">
<div class="row pb-3">
<div class="form-row">
<div class="col-md-3">
<div class="position-relative form-group">
<label class="">Company Name</label> #Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control", #maxlength = "30" } })
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-6">
<div class="position-relative form-group">
<label class="">Reg No</label> #Html.EditorFor(model => model.RegisterNo, new { htmlAttributes = new { #class = "form-control", #maxlength = "15" } })
</div>
</div>
</div>
</div>
</form>
<button name="submit">Save</button>
Controller
public ActionResult Save(Company CompDet){
string Name = CompDet.Name;
string RegNo = CompDet.RegisterNo;
//then Connect DB and Save DB
//HOW TO use SweetAlert before, return RedirectToAction
}
I'm currently using, return RedirectToAction Only.
How to add SweetAlert before RedirectToAction?
Using Ajax Post or Form Post?
Possible that using Ajax & Form Post Together?
After Saving -> Show Sweetalert success -> return redirectToAction
I'm still at the learning level. Please Help.
Thank You

How to make your button on a form using asp.net-mvc work?

I have a button, it does not seem to create new users to my database. What it does it only inherits user validaton to my Login method and need some guidance to this please and thanks. Below is the logic what i am trying to do. What i want to do my create button must be able to create new users if not exist to the database.
Controller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateModel objSubmit)
{
ViewBag.Msg = "Details submitted successfully";
return View(objSubmit);
}
// This is for login, and its hits this method each time.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(Login login)
{
if (ModelState.IsValid)
{
bool success = WebSecurity.Login(login.username, login.password, false);
var UserID = GetUserID_By_UserName(login.username);
var LoginType = GetRoleBy_UserID(Convert.ToString(UserID));
if (success == true)
{
if (string.IsNullOrEmpty(Convert.ToString(LoginType)))
{
ModelState.AddModelError("Error", "Rights to User are not Provide Contact to Admin");
return View(login);
}
else
{
Session["Name"] = login.username;
Session["UserID"] = UserID;
Session["LoginType"] = LoginType;
if (Roles.IsUserInRole(login.username, "Admin"))
{
return RedirectToAction("AdminDashboard", "Dashboard");
}
else
{
return RedirectToAction("UserDashboard", "Dashboard");
}
}
}
else
{
ModelState.AddModelError("Error", "Please enter valid Username and Password");
return View(login);
}
}
else
{
ModelState.AddModelError("Error", "Please enter Username and Password");
return View(login);
}
}
Model:
namespace eNtsaPortalWebsiteProject.Models
{
public class CreateModel
{
[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; }
[Required]
public string username { get; set; }
}
}
// View for login
<div data-="mainContent">
<section class="container">
<div class="logo col-sm-12 text-center col-md-12"> <img alt="" src="~/Images/eNtsa.png" /></div>
<div class="clearfix"></div>
<div class="container">
<div class="row">
<div id="MyWizard" class="formArea LRmargin">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div id="divMessage" class="text-center col-md-12 col-md-offset-12 alert-success">
#Html.ValidationSummary()
</div>
<div class="col-md-12 col-md-offset-10 col-xs-12">
<div class="loginPage panel-info">
<div class="form-group"><span class=""><i class="glyphicon glyphicon-user">Username:</i></span>
#Html.TextBoxFor(model => model.username, new { #class = "form-control text-center", autocomplete = "off" })
#Html.ValidationMessageFor(model => model.username)
</div>
<div class="form-group">
<span class=""><i class="glyphicon glyphicon-lock">Password:</i></span>
#Html.PasswordFor(model => model.password, new { #class = "form-control text-center", autocomplete = "off" })
#Html.ValidationMessageFor(model => model.password)
</div>
</div>
<div class="form-group">
<input id="BtnLogin" type="submit" class="btn btn-success btn-pressure" name="BtnLogin" value="Login" />
<input type ="Submit" class="btn btn-info btn-pressure" name="BtnCreate" value="Create" />
</div>
</div>
}
<div class="clear"></div>
</div>
</div>
</div>
</section>
</div>
View for creating user:
<div class="mainContent">
<section class="container">
<div class="logo col-sm-12 text-center col-md-10">
<img alt="" src="~/Images/eNtsa.png"/>
</div>
<div class="container">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div id="divMessage" class="text-center col-md-12 col-md-offset-12 alert-success">
#Html.ValidationSummary()
</div>
<div class="col-md-12 col-md-offset-10 col-xs-12">
<div class="glyphicon-registration-mark">
<div class="form-group"><span class=""><i class="glyphicon glyphicon-user">Username:</i></span>
#Html.TextBoxFor(model=>model.username, new {#class ="form-control text-center", automplete="off" })
#Html.ValidationMessageFor(model=>model.username)
</div>
<div class="form-group">
<span class=""><i class="glyphicon glyphicon-lock">Password:</i></span>
#Html.PasswordFor(model=>model.password, new {#class = "form-control text-center", autocomplete="off" })
#Html.ValidationMessageFor(model=>model.password)
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-success btn-pressure" name="BtnSubmit" value="Submit"/>
</div>
</div>
}
</div>
</section>
</div>
The button is working - that isn't the problem that you're having.
You can have multiple buttons to submit the form but they will return to the same place, either:
a) the controller/action specified in the "action" property of the form
b) if no action is specified then the default location - in your case there isn't one directly specified so it is posting back to the default location.
(see: How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4)
The easiest way to accomplish what you're trying to do would be refactor your controller and branch the logic depending on what the value is of the submit button.
(see: MVC razor form with multiple different submit buttons?
and How to handle two submit buttons on MVC view)
This will require some refactoring of the code that you have written, but it is the most straightforward way of achieving what you're trying to do.
In very basic terms it would look something like this:
Model:
namespace eNtsaPortalWebsiteProject.Models
{
public class LoginCreateModel
{
[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; }
[Required]
public string username { get; set; }
public string btnSubmit { get; set; } // both buttons will have the same name on your form, with different values ("Create" or "Login")
}
}
Controller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginCreateModel objSubmit)
{
if (objSubmit.btnSubmit == "Create")
{
// Handle creation logic here
}
if (objSubmit.btnSubmit == "Login")
{
// Handle login logic here
}
return View(objSubmit);
}

Search filter using multiple fields showing error in ASP.NET MVC with Entitiy Framework

I am trying to apply search filter in ASP.NET MVC using multiple fields for which I have used view models. I have reached close to it but it is showing this error:
The model item passed into the dictionary is of type 'System.Data.Entity.DbSet`1[HMS.Models.tblPatient]', but this dictionary requires a model item of type 'HMS.ViewModels.SearchViewModel'
I don't know what I am doing wrong.
Here is my code:
SearchController.cs:
public ActionResult Index(SearchViewModel searchModel)
{
var search = new SearchDAL();
var model = search.GetSearchResults(searchModel);
return View(model);
}
ViewModel.cs:
public class SearchViewModel
{
public SearchViewModel()
{
PatientsSearch = new List<SearchResult>();
}
public int? Patient_ID { set; get; }
public string Patient_Name { set; get; }
public string Patient_Address { set; get; }
public string Contact_Number { set; get; }
public int Age { set; get; }
public string Gender { set; get; }
public List<SearchResult> PatientsSearch { set; get; }
}
public class SearchResult
{
public int? Patient_ID { set; get; }
public string Patient_Name { set; get; }
public string Patient_Address { set; get; }
public string Contact_Number { set; get; }
public int Age { set; get; }
public string Gender { set; get; }
}
SearchDAL.cs:
public class SearchDAL
{
private HMS_DBEntity Context;
public SearchDAL()
{
Context = new HMS_DBEntity();
}
public IQueryable<tblPatient> GetSearchResults(SearchViewModel searchModel)
{
var result = Context.tblPatients.AsQueryable();
if (searchModel != null)
{
if (searchModel.Patient_ID.HasValue)
result = result.Where(x => x.Patient_id == searchModel.Patient_ID);
if (!string.IsNullOrEmpty(searchModel.Patient_Name))
result = result.Where(x => x.Patient_Name.Contains(searchModel.Patient_Name));
if (!string.IsNullOrEmpty(searchModel.Patient_Address))
result = result.Where(x => x.Patient_address.Contains(searchModel.Patient_Address));
if (!string.IsNullOrEmpty(searchModel.Contact_Number))
result = result.Where(x => x.Contact_no.Contains(searchModel.Contact_Number));
}
return result;
}
}
Index.cshtml:
#using HMS.ViewModels
#model HMS.ViewModels.SearchViewModel
#*#model HMS.Models.tblPatient*#
#{
ViewBag.Title = "Index";
}
<section class="content">
#using (Html.BeginForm("Index", "Search", FormMethod.Get))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(false, "", new { #class = "text-danger" })
<div class="container-fluid">
<div class="block-header">
<h2>Patients Record</h2>
</div>
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="card">
<div class="body">
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.TextBoxFor(x => x.Patient_ID, new { #type = "Text", #class = "form-control", #id = "PatientID", #placeholder = "Patiend ID" })
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.TextBoxFor(x => x.Patient_Name, new { #type = "Text", #class = "form-control", #id = "PatientName", #placeholder = "Patiend Name" })
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.TextBoxFor(x => x.Patient_Address, new { #type = "Text", #class = "form-control", #id = "PatientAddress", #placeholder = "Patient Address" })
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.TextBoxFor(x => x.Contact_Number, new { #type = "Text", #class = "form-control", #id = "ContactNo", #placeholder = "Contact Number" })
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<input type="submit" id="Submit" class="btn btn-raised g-bg-cyan waves-effect" value="Search" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
<div class="row clearfix">
<div class="container-fluid">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="card">
<div class="body table-responsive">
<table class="table table-bordered table-striped table-hover js-basic-example dataTable">
<tr>
<th>
#Html.DisplayNameFor(model => model.Patient_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Patient_Address)
</th>
<th>
#Html.DisplayNameFor(model => model.Contact_Number)
</th>
<th>
#Html.DisplayNameFor(model => model.Age)
</th>
<th>
#Html.DisplayNameFor(model => model.Gender)
</th>
<th></th>
</tr>
#{
if (Model.PatientsSearch != null && Model.PatientsSearch.Count > 0)
{
foreach (var item in Model.PatientsSearch)
{
<tr>
<td>#item.Patient_Name</td>
<td>#item.Patient_Address</td>
<td>#item.Contact_Number</td>
<td>#item.Age</td>
<td>#item.Gender</td>
</tr>
}
}
}
</table>
</div>
The error message is clear. Your model defined in view Index.cshtml is
#model HMS.ViewModels.SearchViewModel
But the data you pass to the view is result of GetSearchResults, which is System.Data.Entity.DbSet`1[HMS.Models.tblPatient]
var model = search.GetSearchResults(searchModel);
return View(model);
I think you know how to make it works now.
It's a type mismatch issue at:
return View(model);
So, inside GetSearchResults method, make following change while returning the result object:
result = new List<SearchViewModel>(result);
return result;
And, change your return type of GetSearchResults() method from IQueryable to List
public List<SearchViewModel> GetSearchResults(SearchViewModel searchModel)

ASP.NET MVC Multiple form in one page: Validation doesn't work [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am creating a register login page in asp mvc and as i need, this page has two models and two form actions.
every thing is ok but the validation.
the models are:
public class Account_Index_ViewModel
{
public UserAccount_Login_ViewModel userAccount_Login_ViewModel { get; set; }
public UserAccount_Register_ViewModel userAccount_Register_ViewModel { get; set; }
}
public class UserAccount_Login_ViewModel
{
[Required]
[DataType(DataType.Password)]
public string Pass { get; set; }
[Required]
public string LoginName { get; set; } // NickName/Email/MobilePhone
}
public class UserAccount_Register_ViewModel
{
public string NickName { get; set; }
public string Passw { get; set; }
public string PassConfirm { get; set; }
public string Email { get; set; }
public string MobilePhone { get; set; }
}
and the view :
#model GhafasehWebSite.Models.Account_Index_ViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="AccountBook">
<div class="half-width">
#using (Html.BeginForm("Login", "Account"))
{
Html.EnableClientValidation();
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ورود به سیستم</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group col-md-12">
#Html.LabelFor(model => ((GhafasehWebAPI.Models.UserAccount_Login_ViewModel)(model.userAccount_Login_ViewModel)).LoginName, new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.TextBoxFor(model => ((GhafasehWebAPI.Models.UserAccount_Login_ViewModel)(model.userAccount_Login_ViewModel)).LoginName, new { #class = "form-control", placeholder = "نام مستعار/ایمیل/شماره موبایل" })
#Html.ValidationMessageFor(model => ((GhafasehWebAPI.Models.UserAccount_Login_ViewModel)(model.userAccount_Login_ViewModel)).LoginName)
</div>
</div>
<div class="form-group col-md-12">
#Html.LabelFor(model => ((GhafasehWebAPI.Models.UserAccount_Login_ViewModel)(model.userAccount_Login_ViewModel)).Pass, new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.TextBoxFor(model => ((GhafasehWebAPI.Models.UserAccount_Login_ViewModel)(model.userAccount_Login_ViewModel)).Pass, new { #class = "form-control" })
#Html.ValidationMessageFor(model => ((GhafasehWebAPI.Models.UserAccount_Login_ViewModel)(model.userAccount_Login_ViewModel)).Pass)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-10">
<input type="submit" value="ورود" class="btn btn-primary" />
</div>
</div>
</div>
}
</div>
<div class="half-width">
#using (Html.BeginForm("Register","Account"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ثبت نام در سیستم</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group col-md-12">
#Html.LabelFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).NickName, new { #class = "control-label col-md-4" })
<div class=" col-md-8">
#Html.TextBoxFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).NickName, new { #class = "form-control" })
#Html.ValidationMessageFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).NickName)
</div>
</div>
<div class="form-group col-md-12">
#Html.LabelFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).Passw, new { #class = "control-label col-md-4" })
<div class=" col-md-8">
#Html.TextBoxFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).Passw, new { #class = "form-control" })
#Html.ValidationMessageFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).Passw)
</div>
</div>
<div class="form-group col-md-12">
#Html.LabelFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).PassConfirm, new { #class = "control-label col-md-4" })
<div class=" col-md-8">
#Html.TextBoxFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).PassConfirm, new { #class = "form-control" })
#Html.ValidationMessageFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).PassConfirm)
</div>
</div>
<div class="form-group col-md-12">
#Html.LabelFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).Email, new { #class = "control-label col-md-4" })
<div class=" col-md-8">
#Html.TextBoxFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).Email, new { #class = "form-control" })
#Html.ValidationMessageFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).Email)
</div>
</div>
<div class="form-group col-md-12">
#Html.LabelFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).MobilePhone, new { #class = "control-label col-md-4" })
<div class=" col-md-8">
#Html.TextBoxFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).MobilePhone, new { #class = "form-control" })
#Html.ValidationMessageFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).MobilePhone)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-10">
<input type="submit" value="ثبت نام" class="btn btn-success" />
</div>
</div>
</div>
}
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
and the controller:
[HttpGet]
public ActionResult Index()
{
return View(new Account_Index_ViewModel());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserAccount_Login_ViewModel model)
{
if (ModelState.IsValid)
{
if (DataProvider.LoginUser(model, ModelState, Request, Session))
{
return RedirectToAction("Index", "Home");
}
}
return View("Index");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(UserAccount_Register_ViewModel model)
{
if (ModelState.IsValid)
{
if (DataProvider.RegisterUser(model, ModelState, Request, Session))
{
return RedirectToAction("Index", "Home");
}
}
return View("Index");
}
you should know that server side validation works fine but the client side is asleep.
So, what do you suggest?
When you say the validation doesn't work what do you mean? you press Login button with empty username/password and it doesn't show required error?
If so , I Created new project with your model view controller and it worked !!! The validation works.

Field required attribute acidentially invoked but clicking a button

I have these fields, and I implemented required attribute on them.
#using (Html.BeginForm("Edit", "ChannelsGrid", FormMethod.Post, new {name = "channelForm", #class = "channelForm", #enctype = "multipart/form-data"}))
{
<div class="form-group">
#Html.HiddenFor(model => Model.Id)
<div class="row">
<div class="col-md-6">
#Html.Label("Part/Location", new {#class = "control-label"})
#Html.TextBox("PartLocation", null, new { #class = "form-control", #required = "required" })
</div>
<div class="col-md-6">
#Html.Label("Index", new {#class = "control-label"})
#Html.TextBox("Index", null, new {#class = "form-control"})
</div>
</div>
<div class="row">
<div class="col-md-6">
#Html.Label("Measurement", new {#class = "control-label"})
#Html.DropDownListFor(model => model.Measurement, (SelectList)ViewBag.Measurements, "-- Select Measurement --", new { #class = "form-control", #required = "required" })
</div>
<div class="col-md-6">
#Html.Label("Location", new {#class = "control-label"})
#Html.DropDownList("Directions", ViewBag.DirectionTypes as List<SelectListItem>, "-- Select Direction --", new { #class = "form-control", #required = "required" })
</div>
</div>
<div class="row">
<div class="col-md-6">
#Html.LabelFor(model => model.ChannelGroupId, new {#class = "control-label"})
#Html.DropDownListFor(x => x.ChannelGroupId, Model.ChannelGroups, "Select Channel Group", new {#class = "form-control"})
#Html.ValidationMessageFor(model => model.ChannelGroupId)
</div>
<div class="col-md-3">
<label class="control-label"></label>
<a href="#" id="addChannelGroup" class="form-control" style="border: none">
<i class="fa fa-plus-circle">Add Group</i>
</a>
</div>
<div class="col-md-3">
<label class="control-label"></label>
<a href="#" id="addMeasurement" class="form-control" style="border: none">
<i class="fa fa-plus-circle">Add Measurement</i>
</a>
</div>
</div>
<br/>
<div class="row">
<div class="col-md-6">
#Html.Label("Channel name: ", new {id = "channelName", #class = "control-label"})
</div>
<div class="col-md-6">
#Html.TextBox("HiddenTextBox", null, new {#class = "hidden"})
<div class="col-md-1">
#Html.TextBoxFor(a => a.Name, new {#class = "hidden"})
</div>
</div>
</div>
</div>
<div class="row" id="pnlAddChannelGroupName" style="display: none">
<div class="col-md-6">
<label class="control-label">Channel Group Name :</label>
<input type="text" id="ChannelGroupName" name="ChannelGroupName" class="form-control"/>
<input type="button" value="Cancel" id="channelGroupButton" />
#*<button id="channelGroupButton">Cancel</button>*#
</div>
</div>
<div class="row" id="pnlMeasurement" style="display: none">
<div class="col-md-6">
#Html.Label("Measurement :", new {#class = "control-label"})
#Html.TextBox("MeasurementName", null, new {#class = "form-control"})
<input type="button" value="Cancel" id="measurementButton" />
#*<button id="measurementButton">Cancel</button>*#
</div>
</div>
}
I also have two buttons which are used to toggle other textboxes in this form. Here is the code.
<div class="row" id="pnlAddChannelGroupName" style="display: none">
<div class="col-md-6">
<label class="control-label">Channel Group Name :</label>
<input type="text" id="ChannelGroupName" name="ChannelGroupName" class="form-control"/>
<button id="channelGroupButton">Cancel</button>
</div>
</div>
<div class="row" id="pnlMeasurement" style="display: none">
<div class="col-md-6">
#Html.Label("Measurement :", new {#class = "control-label"})
#Html.TextBox("MeasurementName", null, new {#class = "form-control"})
<button id="measurementButton">Cancel</button>
</div>
</div>
The problem is whenever I click these two Cancel buttons in that field, the three fields seems to be invoked and there is brown border around the textbox dropdownlist. I guess these field have been submitted. But I thought I use button element instead of type button of an input so I can eliminate the submitting action of the button, right? Any clues? And how can I click these Cancel buttons withouts invoking validation in these other field?
Edited: I changed all the buttons to input type="button" and the validation of these other field dissapeared. Can someone explain?
This is my viewmodel:
namespace CrashTestScheduler.Entity.ViewModel
{
public class ChannelViewModel
{
public int Id { get; set; }
//[Display(Name = "Name")]
//[Required(ErrorMessage = "Please specify the channel name.")]
public string Name { get; set; }
public string Description { get; set; }
public string ChannelGroupName { get; set; }
public string MeasurementName { get; set; }
[Required(ErrorMessage = "Please select a channel group.")]
public int ChannelGroupId { get; set; }
public IEnumerable<SelectListItem> ChannelGroups { get; set; }
//[Required]
public string Measurement { get; set; }
}
}
The reason your form is submitting when clicking buttons is that the default action for a <button> element is type="submit" (refer documentation). You need to explicitly set the type attribute
<button type="button" ....>
However you have numerous issues with your approach.
By removing the [Required] attributes and using the required =
"required" html attribute, you now need to include manual
validation on the controller (never trust the user!)
Your mixing up Razor and manual html in the view, potentially
creating problems for model binding. Some of your label elements
wont work. (e.g. the first one is associated with a control named
"Part/Location" but there is no control named "Part/Location").
The user interface where your force users to click buttons to swap
between textboxes and dropdown lists is confusing and a sure way to
lose customers. Instead you should use an autocomplete control such
as jQuery Autocomplete which allows selection from a list or
direct text entry.
Your view model should contain validation attributes for its properties and can be simplified to
public class ChannelViewModel
{
public int Id { get; set; }
[Display(Name = "Part/Location")]
[Required]
public string PartLocation { get; set; }
public string Index { get; set; }
[Required]
public string Measurement { get; set; }
[Required]
[Display(Name = "Location")]
public int Direction { get; set; }
.... // other properties
public SelectList DirectionList { get; set; }
}
View
#Html.HiddenFor(model => Model.Id)
#Html.LabelFor(m => m.PartLocation, new {#class = "control-label"})
#Html.TextBoxFor(m => m.PartLocation, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.PartLocation)
#Html.LabelFor(m => m.Index, new {#class = "control-label"})
#Html.TextBoxFor(m => m.Index, new {#class = "form-control"})
#Html.LabelFor(m => m.Measurement, new {#class = "control-label"})
#Html.TextBoxFor(m => m.Measurement, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Measurement)
#Html.LabelFor(m => m.Direction, new {#class = "control-label"})
#Html.DropDownListFor(m => m.Direction, Model.DirectionList, "-- Select Direction --", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Direction)
.... // more controls
The attach the autocomplete to $(#Measurement).autocomplete({...
This will give you client and server side validation out of the box, and a better user interface.

Resources