I want to validate #Html.EditorFor that it is required to input, but not working in asp.net mvc
<div class="form-group"> <label>First Name editor*</label>
#Html.EditorFor(x => x.Requester.FirstName, new { #class = "form-control", required = "required" })
#Html.ValidationMessageFor(m => m.Requester.FirstName)
</div>
sorry for my simple question because it is really frustating try to fix this issue
my controller code
[HttpPost]
public ActionResult Index(ViewModel.Ticket m)
{
try
{
using (DatabaseManager ctx = new DatabaseManager(true))
{
if (string.IsNullOrEmpty(m.TicketNo))
{
m.TicketNo = TicketNo.Create(User.Identity.Name, "TICKET");
}
Ticket obj = ViewModel.Ticket.ConvertToTicketBusiness(m);
obj.Requester = m.Requester.Email;
obj.TicketStatus = TicketStatus.Open.ToString();
obj.Escalation = User.Identity.Name;
obj.CreatedBy = User.Identity.Name;
obj.CreatedDate = DateTime.Now;
obj.UpdatedBy = obj.CreatedBy;
obj.UpdatedDate = obj.CreatedDate;
if (obj.IsValid)
{
obj = obj.Save();
}
Customer cust = ViewModel.Ticket.ConvertToCustomerBusiness(m.Requester);
if (string.IsNullOrEmpty(cust.CreatedBy))
{
cust.CreatedBy = User.Identity.Name;
cust.CreatedDate = DateTime.Now;
}
cust.UpdatedBy = User.Identity.Name;
cust.UpdatedDate = DateTime.Now;
if (cust.IsValid)
{
cust = cust.Save();
}
ctx.SaveChanges();
}
ViewBag.SuccessMsg = "Success";
}
catch (Exception ex)
{
ViewBag.ErrorMsg = ex.Message;
return View(m);
}
return RedirectToAction("Inbox");
}
thank you
Insert # Like: #required="required"
This is how it worked for me (ASP.NET MVC 5). Add
#data_val="true"
with
#required="required"
Final code:
#Html.EditorFor(model => model.FullName, new { htmlAttributes = new { #class = "form-control", #data_val="true", #required="required" } })
by adding , the form started to use jquery validator.
When you want to validate mandatory form input do not use EditorFor() if your MVC bellow 5.1, just using TextBoxFor() thank you
Related
I create kendo grid in my view but there`s no value display in my kendo grid and this is my code in chtml
<div style="width:100%;height:100%">
#(Html.Kendo().Grid<TBSWebApp.Models.DisplayRecords>()
.Name("BindGridUsingRead")
.DataSource(DataSource => DataSource.Ajax()
.Model(Model => Model.Id(m => m.InvoiceNo))
.Read(read => read.Action("BindGrid2", "Invoice")))
.Columns(columns =>
{
columns.Bound(p => p.InvoiceNo).Width(15).Title("Invoice
No.").Filterable(false);
columns.Bound(p => p.InvoiceDate).Title("Invoice
Date").Width(15).Filterable(false);
columns.Bound(p => p.FileAs).Title("Client
Name").Width(50).Filterable(false);
columns.Bound(p =>
p.Amount).Title("Amount").Width(15).Filterable(false);
})
.Pageable()
.Sortable()
)
</div>
and i have controlled which i call for my database in sql and this is the code is to bind my kendo grid to display my database and convert into json.
public ActionResult BindGrid2([DataSourceRequest]DataSourceRequest request)
{
try
{
string FileAs = "";
List<Models.DisplayRecords> lst = new List<Models.DisplayRecords>();
lst = GetGridData(FileAs).ToList();
DataSourceResult result = lst.ToDataSourceResult(request, p => new Models.DisplayRecords
{
InvoiceNo = p.InvoiceNo,
InvoiceDate = p.InvoiceDate,
FileAs = p.FileAs,
Amount = p.Amount,
});
//return Json(result, JsonRequestBehavior.AllowGet);
return Json(result);
}
catch (Exception ex)
{
var errorMsg = ex.Message.ToString();
return Json(errorMsg, JsonRequestBehavior.AllowGet);
}
}
and this one is to call sql server connection and select from the table that i want to bind it
public IEnumerable<Models.DisplayRecords> GetGridData(string ClientName)
{
List<Models.DisplayRecords> objCmp = new List<Models.DisplayRecords>();
List<Models.DisplayRecords> listCompany = new List<Models.DisplayRecords>();
string strServer = GlobalVariable.prServer;
string strDatabase = GlobalVariable.prDatabase;
string mainconn = string.Format(ConfigurationManager.ConnectionStrings["BackendEntities"].ConnectionString, strServer, strDatabase);
SqlConnection sqlconn = new SqlConnection(mainconn);
string s1 = "SELECT InvoiceNo,InvoiceDate,FileAs,LoanBalance FROM tblInvoice LEFT OUTER JOIN tblContacts ON tblInvoice.CustomerID = tblContacts.ContactID WHERE LEFT(InvoiceNo,2) ='LR'";
SqlCommand sqlcomm = new SqlCommand(s1);
sqlcomm.Connection = sqlconn;
sqlconn.Open();
SqlDataReader sdr = sqlcomm.ExecuteReader();
List<DisplayRecords> objmodel = new List<DisplayRecords>();
if (sdr.HasRows)
{
while (sdr.Read())
{
objCmp.Add(new Models.DisplayRecords() { InvoiceNo = sdr["InvoiceNo"].ToString(), InvoiceDate = sdr["InvoiceDate"].ToString(), FileAs = sdr["FileAs"].ToString(), Amount = sdr["LoanBalance"].ToString() });
}
sqlconn.Close();
}
if (ClientName != "")
{
listCompany = objCmp.ToList().Where(a => a.FileAs == ClientName).ToList();
return listCompany.AsEnumerable();
}
return objCmp.ToList().AsEnumerable();
}
but the result is still no data display in my kendo grid. I dont know why but when i try to break point on my controller action the "public ActionResult BindGrid2" is not passing by and this is the result of running web view:
Click to view Image
This Is My Controller
[HttpPost]
public ActionResult Create([Bind] Employee emp, HttpPostedFileBase Photo)
{
try
{
if (Photo.ContentLength > 0)
{
string _ImageName = Path.GetFileName(Photo.FileName);
string _path = Path.Combine(Server.MapPath("~/Upload/" + _ImageName), _ImageName);
Photo.SaveAs(Server.MapPath(_path));
objemployee.AddEmployee(emp);
ViewBag.Message = "Image Uploaded Successfully!!";
return View();
}
else if (ModelState.IsValid)
{
objemployee.AddEmployee(emp);
return RedirectToAction("Index");
}
return View(emp);
}
catch
{
objemployee.AddEmployee(emp);
//return Json(new { msg = "1" }, JsonRequestBehavior.AllowGet);
return View();
}
}
code for add data
public void AddEmployee(Employee emp)
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("spaddEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FirstName", emp.FirstName);
cmd.Parameters.AddWithValue("#LastName", emp.LastName);
cmd.Parameters.AddWithValue("#Gender", emp.Gender);
cmd.Parameters.AddWithValue("#DOB", Convert.ToDateTime(emp.DOB));
cmd.Parameters.AddWithValue("#Hobby", emp.Hobby);
cmd.Parameters.AddWithValue("#Photo", emp.Photo);
cmd.Parameters.AddWithValue("#City", emp.City);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
following is my creat and Index view , data show on Index page
#Html.LabelFor(model => model.Photo, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.TextBox("Photo", "", new { type = "file" })
#Html.ValidationMessageFor(model => model.Photo, "", new { #class = "text-danger" })
You have to store not only image name but also Path for the same image into database.
For more details refer a below URL with an example:
https://www.aspsnippets.com/Articles/Display-Images-inside-WebGrid-in-ASPNet-MVC.aspx
add FormMethod.post method in creat view
I've got a text box that upon initial page load (and assuming an empty model) the html TextBoxFor helper populates a text box with 0. Since 0 is a value, I want to change this behavior to "" (null, nothing, etc.). Given the amount of literature out there on this, I thought this should be straightforward; however, I can't get it to work. Here's what I've got (I've parsed it down to keep it simple, pardon any mistakes)
Model:
public class Something_ViewModel
{ [DisplayName("Feet:")]
public int Feet{ get; set; }
}
Controller:
public IActionResult RetainedOwnership()
{
Models.Analytics.Something_ViewModel RO_VM = new Models.Analytics.Something_ViewModel();
Return View(RO_VM);
}
And the tag Helpers I've tried:
#Html.TextBoxFor(Model => Model.Feet, new { id = "txtFeet", #Value = Model.Feet.ToString() ?? "" })
#Html.TextBoxFor(Model => Model.Feet, new { id = "txtFeet", Value = Model.Feet.ToString() ?? "" })
#Html.TextBoxFor(Model => Model.Feet, new { id = "txtFeet", Value = "" })
#Html.TextBoxFor(Model => Model.Feet, new {Value = "" })
#Html.TextBoxFor(Model => Model.Feet, new {#Value = "" })
#Html.TextBoxFor(Model => Model.Feet, new {id = "txtFeet"})
You might want to change Feet datatype to int?. Default value for that would be null.
I want to change the value in my EditorFor to a value from my DB, based on a selection from my DropDownFor.
Code to pull value to go into TextboxFor in my Controller:
using (RexusTradingEntities RTE = new RexusTradingEntities())
{
if (PIVM.Pipe_Absolute_Roughness_Override != null || PIVM.Pipe_Absolute_Roughness_Override != 0)
{
PIVM.Pipe_Absolute_Roughness = Convert.ToDecimal(PIVM.Pipe_Absolute_Roughness_Override);
}
else
{
var PipeAbsoluteRoughness = (from P in RTE.ProjectInformations
join PM in RTE.PipeMaterials on P.Pipe_Material equals PM.Material_Name
where P.pkiProjectID == id
select PM).SingleOrDefault();
PIVM.Pipe_Absolute_Roughness = Convert.ToDecimal(PipeAbsoluteRoughness.Material_Value);
}
}
View:
#Html.EditorFor(model => model.Pipe_Absolute_Roughness, new { htmlAttributes = new { #class = "form-control col-md-5" } })
This works when loading the View the first time, but I want the value in the EditorFor to change when ever the DropDownFor selected value changes.
I would like this same EditorFor value to change when the following EditorFor Value changes :
#Html.EditorFor(model => model.Pipe_Absolute_Roughness_Override, new { htmlAttributes = new { #class = "form-control" } })
I would appreciate the help, as I am still pretty new to MVC and still learning the ropes.
Thanks for any help.
Got it sorted. I am posting what I did below. Please note that I am only providing the specific items I used, not everything(for example, I did not post the entire View, only the parts I used)
View :
#Html.DropDownListFor(model => model.Pipe_Material, Model.Pipe_MaterialList, new { #class = "form-control", id = "ddlPipe_Material", #onchange = "ChangePipeMaterialValue(this.value)" })
#Html.EditorFor(model => model.Pipe_Absolute_Roughness, new { htmlAttributes = new { #class = "form-control col-md-5", #id = "txtPipe_Absolute_Roughness" } })
#section scripts
{
<script src="#Url.Content("~/bootstrap.min.js")"></script>
<script src="#Url.Content("~/jquery-2.2.3.min.js")" type="text/javascript"></script>
<script>
function ChangePipeMaterialValue(val) {
//var Pipe_Material = $("#ddlPipe_Material").val();
var ProjectDetails =
{
"Pipe_Material": val
};
$.ajax({
url: '/ProjectInformation/GetPipeMaterialValues/',
data: JSON.stringify(ProjectDetails),
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) {
var m = $('#txtPipe_Absolute_Roughness');
m.val(data);
}
});
}
</script>
}
Controller :
[HttpPost]
public JsonResult GetPipeMaterialValues(ProjectInformationViewModel model)
{
decimal PipeMaterialValue;
using (RexusTradingEntities RTE = new RexusTradingEntities())
{
var PipeMaterialValueQuery = (from PM in RTE.PipeMaterials
where PM.Material_Name == model.Pipe_Material
select PM).FirstOrDefault();
PipeMaterialValue = Convert.ToDecimal(PipeMaterialValueQuery.Material_Value);
}
return Json(PipeMaterialValue, JsonRequestBehavior.AllowGet);
}
In fact, I do not even need to pass the model through to the Controller, I can just pass the parameter "val" through to the URL as well, but I am leaving it as is, as it does the job. I hope this helps someone else in the future.
#Html.EditorFor(model => model.Pipe_Absolute_Roughness_Override, new { htmlAttributes = new { #Value=#Html.ValueFor(x=>x.Pipe_Absolute_Roughness) , #class = "form-control" } })
this is not a dropdown, but it can also be useful
I need to insert a default value at the top of the result I have as below....
Can someone give me a clue how to do it with an anonymous type?
public JsonResult GetThingsForStuff(string stuff)
{
var things= from c in db.MYTABLE
where c.idofstuff == stuff
select new { id = c.realid, name = c.realname};
return Json(things, JsonRequestBehavior.AllowGet);
}
In my controller I do this initially by
List<SelectListItem> items3 = new SelectList(db.MYTABLE.ToList().Distinct(), "realid", "realname").ToList();
items3.Insert(0, (new SelectListItem { Text = "Select Me", Value = "0" }));
ViewBag.Things = items3;
by I have a javascript function reloading this dropdownlist based on the selected "stuff" and I need this default back at the top.
Any help would be greatly appreciated.
Thanks,
David
You could concatenate them:
public JsonResult GetThingsForStuff(string stuff)
{
var things = db
.MYTABLE
.Where(x => x.idofstuff == stuff)
.ToList()
.Select(x => new SelectListItem
{
Value = x.realid.ToString(),
Text = x.realname
});
var items = new[] { new SelectListItem { Text = "Select Me", Value = "0" } }
.Concat(things);
return Json(items, JsonRequestBehavior.AllowGet);
}