I have this view :
<div class="form-horizontal">
<h4>Giriş</h4>
<hr />
<div class="form-group">
#Html.Label("TCKimlikNo","TC Kimlik No :", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.Editor("TCKimlikNo", new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<hr />
<div class="form-group">
#Html.Label("Sifre", "Şifre :", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.Password("Sifre", new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
And it looks like this :
I want to make Sifre look like the textbox above. And I want that textbox to be empty. How can I do that? Thanks in advance.
You are calling the (string name, Object value) overload, so your anonymous object's ToString() goes into the textbox as the value.
Apparently you wanted to call the (string name, Object value, Object htmlAttributes) overload:
#Html.Password("Sifre", null, new { #class = "form-control" })
Related
I'm new to MVC asp.net jquery ajax and hoping you guys can help me give insight on my problem.
Thank you so much any answer would be helpful.
I'm just having a self exercise that i saw on some online group to help me gain more knowledge on how to implement jquery on asp.net mvc any advice would help.
Controller
public JsonResult AddJob(jobdetail job)
{
using(jQueryAjaxEntities db = new jQueryAjaxEntities())
{
db.jobdetails.Add(job);
db.SaveChanges();
return Json("Success");
}
}
Heres my AddJob view
Whenever I remove the script src it's saving normally, can anyone explain me why is it like that?
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function () {
$("#btnSave").click(function () {
var JobModel = {
TaskName: $("Task_Name").val(),
Description: $("Description").val(),
DateStarted: $("Date_Started").val(),
DateFinished: $("Date_Finished").val(),
Status: $("Status").val()
};
$.ajax({
type: "POST",
url: "/Home/AddJob",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({ job: JobModel }),
success: function (response) {
window.location.href = "/Home/Index"
}
});
});
});
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.JobID)
<div class="form-group">
#Html.LabelFor(model => model.Task_Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Task_Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Task_Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date_Started, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date_Started, new { htmlAttributes = new { #class = "form-control", #type = "date" } })
#Html.ValidationMessageFor(model => model.Date_Started, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date_Finished, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date_Finished, new { htmlAttributes = new { #class = "form-control", #type = "date" } })
#Html.ValidationMessageFor(model => model.Date_Finished, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Status, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Status, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Status, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" id="DivSave">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Submit" id="btnSave" class="btn btn-default" />
</div>
</div>
</div>
}
You are probably hitting your AddJob Action twice. First, the btnSave button is clicked, and by the jquery event, you post your data with ajax. Then, your form submits the data to your AddJob Action as well. And a duplicate record is inserted.
You posting your form twice.
1.#(Html.BeginForm()) Post call as button type is submit.
which is working fine and inserting proper data.
2.jQuery AJAX Post Call.
Missing # for getting values of fields.
So, It inserting Null data.
Code:
TaskName: $("Task_Name").val()
It should be:
TaskName: $("#Task_Name").val()
If you made this changes then it will insert data twice.
So, You need to post form once only.
This can be done:
Change Button type sumit to button. This will avoid post call of form begin.
Remove Jquery post code.
I will suggestions Remove AJAX call code post your form using form post only.
FYI, I am also populating a field model.VdiId from a partial page using jQuery. When I am clicking the submit button of the form page, It is redirecting me to a blank page, instead of hitting the BookVdi action of Booking controller. I am throwing exception and putting breakpoints which are not hitting as well.
Below is the View Code:
#model HVDI.Models.BookingViewModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (#Html.BeginForm("BookVdi", "Booking", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<h4>Booking</h4>
<hr />
<div class="form-inline">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.VdiId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.VdiId, new { htmlAttributes = new { #class = "form-control disabled" } })
#Html.ValidationMessageFor(model => model.VdiId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookingDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingDate, new { htmlAttributes = new { #class = "form-control datepicker" } })
#Html.ValidationMessageFor(model => model.BookingDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TimeStart, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TimeStart, new { htmlAttributes = new { #class = "form-control timepicker" } })
#Html.ValidationMessageFor(model => model.TimeStart, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TimeEnd, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TimeEnd, new { htmlAttributes = new { #class = "form-control timepicker" } })
#Html.ValidationMessageFor(model => model.TimeEnd, "", new { #class = "text-danger" })
</div>
</div>
<div class="showing">
<input type="button" class="align-content-end" onclick="" id="btnSearch" value="Search" />
</div>
</div>
<br />
<div class="form-group">
<div class="table-dark" id="vdiSection">
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Book" class="btn btn-default" />
</div>
</div>
}
Below is the Controller code:
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public void BookVdi(BookingViewModel bookingDetails)
{
if (!ModelState.IsValid)
{
throw new Exception();
}
Booking newBooking = new Booking();
newBooking.BookingDate = bookingDetails.BookingDate; //I am putting a breakpoint here
}
It is opening a blank page:
http://localhost:61110/Booking/BookVdi
You see empty page because you might not return anything when action executed properly. Please change your code as per below.
[HttpPost]
[ValidateAntiForgeryToken]
public void BookVdi(BookingViewModel bookingDetails)
{
if (!ModelState.IsValid)
{
ViewBag,Error = "Please, correct all errors.";
return View("YOURVIEWNAMEFOR FORM");
}
Booking newBooking = new Booking();
newBooking.BookingDate = bookingDetails.BookingDate;
// Write save code here
return RedirectToAction("Index"); // you must redirect to something when action executed.
}
Also add this ViewBag to see errors on view
#Html.AntiForgeryToken()
#Html.ValidationSummary()
#ViewBag.Error // add this line
<h4>Booking</h4>
Also look at this question if you need specific model errors to be shown in view question
I've been trying to get this problem fixed for several hours now, but can't seem to find out what's wrong here.
I have a view with a few fields that I want to post to my controller. Now, I want to check for validation errors on the client side. I've used this in several projects before by adding:
- jquery.js (version 1.12.1)
- jquery.validate.js (version 1.14.0)
- jquery.validate.unobtrusive.js (version 3.2.3)
- jquery-unobtrusive-ajax.js (version 3.2.3)
As soon as a I reference jquery.validate.unobtrusive.js, the client sided validation works. But when I press the submit button, it just won't submit the form anymore. It just won't hit the controller.
My view is as following:
<div class="row">
<div class="col-md-12">
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject bold uppercase font-dark">Auto toevoegen</span>
</div>
<div class="actions">
#Html.ActionLink("Terug", "Index", null, new { #class = "btn btn-circle green btn-outline btn-sm" })
</div>
</div>
<div class="portlet-body">
#using (Html.BeginForm("Create", "Car", FormMethod.Post, new { #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Merk, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Merk, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Merk)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Type, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Type, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Type)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Kenteken, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Kenteken, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Kenteken)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Kilometervergoeding, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Kilometervergoeding, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Kilometervergoeding)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AccountNumber, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AccountNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AccountNumber)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DefaultCar, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DefaultCar)
#Html.ValidationMessageFor(model => model.DefaultCar)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Opslaan" class="btn blue" />
#Html.ActionLink("Annuleren", "Index", null, new { #class = "btn btn-white" })
</div>
</div>
</div>
}
</div>
</div>
</div>
My controller action looks like this:
[HttpPost]
[DisableValidation]
public ActionResult Create(CarViewModel model)
{
if(!ModelState.IsValid)
{
return View(model);
}
try
{
var tblCar = mapper.Map<CarViewModel, tblCar>(model);
_carAppService.Insert(tblCar);
return RedirectToAction("Index");
}
catch(Exception ex)
{
//Add proper error messages
Logger.Debug("Error occured during car adding process: " + ex.InnerException);
//add common container with errors
TempData["Error"] = "Er is iets fout gegaan :(";
return RedirectToAction("Index");
}
}
The scripts are loading in a bundle on startup and are loading in the order stated above. Now as soon as I remove the jquery.validate.unobtrusive from my bundle config, the submit button works. The client sided validation doesn't work anymore then though.
Does any know what's going on here? Thanks!
Alright I fixed the problem!
This answer will most likely only be useful is you make use of ASP.NET Boilerplate Zero template.
In ~/Common/Scripts a Javascript file was added (jquery-validation-custom.js).
The content messed with the submit button. I replaced it with my own version of a custom validation handler for modals and now it works!
I have a view which contains two partial views. One to select a customer and one to create a new customer both shown within tabs on the parent page. If somebody selects a customer, and then continues with the data entry form, but then has to go back to create a new customer instead, then the data from the selected customer remains. I can replace the data by entering the new data, however, the important bit is that the customer id remains and therefore none of the other data is taken into account. Is there a way for me to reset the customer object on click of e.g. an edit button without losing data from the rest of the page?
My parent view (relevant section) is:
<div class="form-group">
#Html.LabelFor(model => model.CommunicationModel.Communication.Customer.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-12">
#if (Model.CommunicationModel.Communication.Customer.Name == null)
{
<input id="btnCust" type="button" value="Select" class="btn btn-default selectCustomer" />
}
else
{
<span id="custSpan" style="font-size:16px; font:bold;">
#Html.DisplayFor(model => model.CommunicationModel.Communication.Customer.Name)
#Html.HiddenFor(model => model.CommunicationModel.Communication.Customer.CustomerId)
<input id="btnEditCust" type="button" value="Edit" class="btn btn-default selectCustomer" />
</span>
}
<div id="customerTabs" style="display:none;">
<hr />
<p>
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active">Select Customer</li>
<li role="presentation">Create New Customer</li>
</ul>
</p>
<div class="tab-content">
<div id="tabs-1" role="tabpanel" class="tab-pane active">
#Html.Partial("~/Views/Communication/SelectCustomer.cshtml", Model.CustomerViewModel.AllCustomers)
</div>
<div id="tabs-2" role="tabpanel" class="tab-pane">
#Html.Partial("~/Views/Communication/CreateCustomer.cshtml", Model)
</div>
</div>
</div>
</div>
</div>
And my create customer partial view is:
#model CommunicationsLog.ViewModels.CommunicationViewModel
<div class="form-horizontal" id="addCustomerForm">
<div class="row">
<div class="col-md-12">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CommunicationModel.Communication.Customer.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CommunicationModel.Communication.Customer.Name, new { htmlAttributes = new { #class = "form-control" }, #id = "name" })
#Html.ValidationMessageFor(model => model.CommunicationModel.Communication.Customer.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CommunicationModel.Communication.Customer.ContactEmail, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CommunicationModel.Communication.Customer.ContactEmail, new { htmlAttributes = new { #class = "form-control" }, #id = "email" })
#Html.ValidationMessageFor(model => model.CommunicationModel.Communication.Customer.ContactEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CommunicationModel.Communication.Customer.ContactTel, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CommunicationModel.Communication.Customer.ContactTel, new { htmlAttributes = new { #class = "form-control" }, #id = "phone" })
#Html.ValidationMessageFor(model => model.CommunicationModel.Communication.Customer.ContactTel, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CommunicationModel.Communication.Customer.CompanyName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CommunicationModel.Communication.Customer.CompanyName, new { htmlAttributes = new { #class = "form-control" }, #id = "company" })
#Html.ValidationMessageFor(model => model.CommunicationModel.Communication.Customer.CompanyName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CommunicationModel.Communication.Customer.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CommunicationModel.Communication.Customer.Address, new { htmlAttributes = new { #class = "form-control" }, #id = "address" })
#Html.ValidationMessageFor(model => model.CommunicationModel.Communication.Customer.Address, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
Any help would be greatly appreciate. Im stumped :)
You're using Partials, meaning the html already been loaded and rendered when it reach the client.
To handle the case of Id is being sent, you should mark ..Customer.CustomerId has disabled="disabled" or readonly, this will avoid the Client side of submitting the Input tag, which will result of the Server side "think" (If you implemented it in that fashion) that this is a new customer.
You can easily achieve it using jQuery 1.6+:
$('#TheCustomerId').prop('disabled', true);
$('#TheCustomerId').prop('disabled', false);
Disable on < 1.6: Disable/enable an input with jQuery?
I'm doing a form that contains a List<object>. This List<object> must be sent to the controller but I don't want to use JSON. Is it possible? Do I have to test with id="MyField[i]" or anything like that?
Here is the Razor code that is targeted:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Ajout de Critères sur l'audit #Model.idAudit</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#foreach (var item in Model.criteresList)
{
<div class="form-group">
#Html.LabelFor(model => item.nomCritere, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => item.nomCritere, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => item.nomCritere, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => item.libelle, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => item.libelle, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => item.libelle, "", new { #class = "text-danger" })
</div>
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
And the Controller
[HttpPost]
public ActionResult Criteres(CritereViewModel model)
{
// Call BL to save them all
return RedirectToAction("Index");
}
Well this article explains everyting about binding arrays in MVC
If you want to post your form values with bare hands you need to do something like this:
#for (var i = 0 ;i < in Model.criteresList.Count();i++)
{
#Html.EditorFor(model => Model.criteresList[i].nomCritere, new { htmlAttributes = new { #class = "form-control" } })
}
the previous answer is viable and what you say also works (id = "MyField [i]") you just have to add the object properties.
#Html.Hidden(string.Format("model.criteresList[{0}].nomCritere", index),someValue)
<select name="model.criteresList[#index].nomCritere" value="someValue">
in controller
[HttpPost]
public ActionResult Criteres(CritereViewModel model)
{}