Was receiving this error:
An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code
Additional information: DataBinding: 'Final.Models.Hello' does not contain a property with the name '700'.
I looked through google for some answers, but I still feel lost.
Model class:
public Hello () {
db = new ExtensionDBEntities();
}
public List<Hello> getID()
{
var que = (from rel in db.Table1
select new Hello
{
ID = rel.ID
}).ToList();
return que;
}
public List<Hello> getStuff()
{
var que = (from wre in db.View
select new Hello
{
ID = wre.ID,
Summary = wre.Summary,
Description = wre.Description
}
}
getHello() is the same exact method as the getStuff(), just accepts a string ID parameter.
Controller class:
public ActionResult Index()
{
var model = test.getStuff();
ViewBag.Releases = new SelectList(test.getID(), "", "ID");
ViewBag.Managers = new SelectList(test.getManagers(), "", "Managers");
return View("");
}
[HttpPost]
public ActionResult Selection()
{
string selectedId = Request["IDText"].ToString();
string Managers = Request["ManagersText"].ToString();
var model = test.getStuff();
ViewBag.Releases = new SelectList(test.getID(), selectedId, "ID");
ViewBag.Managers = new SelectList(test.getManagers(), Managers, "Managers");
var que = test.getHello(selectedId, Managers);
return View(que);
}
Index View Class:
$(document).ready(function () {
$("#Releases").on("change", function () {
var value = $('#Releases :selected').text()
$("#IDText").val(value);
});
$("#Managers").on("change", function () {
var value = $('#Managers :selected').text()
$("#ManagersText").val(value);
});
});
#using (Html.BeginForm("Selection", "Sample", FormMethod.Post))
{
<div class="container" id='div_release'>
#Html.DropDownList("Releases", ViewBag.Releases as SelectList)
#Html.DropDownList("Managers", ViewBag.Managers as SelectList)
#Html.Hidden("IDText", "")
#Html.Hidden("ManagersText", "")
<input type="submit" name="Submit" id="btnUploadData" class="btn btn-primary" value="Upload" />
</div>
}
Selection View Class:
<div class="container">
<table id="myTable" align="left">
<tr>
<th>#Html.DisplayNameFor(model => model.ID)</th>
<th>#Html.DisplayNameFor(model => model.Summary)</th>
<th>#Html.DisplayNameFor(model => model.Description)</th>
</tr>
#foreach (var item in Model)
{
<tr id="Home">
<td>#Html.DisplayFor(x => item.ID)</td>
<td>#Html.DisplayFor(x => item.Summary)</td>
<td>#Html.DisplayFor(x => item.Description)</td>
</tr>
}
$(document).ready(function () {
$("#Releases").on("change", function () {
var value = $('#Releases :selected').text()
$("#IDText").val(value);
});
$("#Managers").on("change", function () {
var value = $('#Managers :selected').text()
$("#ManagersText").val(value);
});
});
#using (Html.BeginForm("Selection", "Sample", FormMethod.Post))
{
<div class="container" id='div_release'>
#Html.DropDownList("Releases", ViewBag.Releases as SelectList) // Getting the error here....
#Html.DropDownList("Managers", ViewBag.Managers as SelectList)
#Html.Hidden("IDText", "")
#Html.Hidden("ManagersText", "")
<input type="submit" name="Submit" id="btnUploadData" class="btn btn-primary" value="Submit" />
</div>
}
</table>
</div>
The error occurs in the Selection View Class. The View classes are almost identical, the only difference being is the data being displayed in the Selection View Class based on the selected value from the drop down list.
Here is a link to a fiddle that combines the views into one: https://dotnetfiddle.net/5uCKhI
This should help you. Please let me know if there is anything else.
Controller/Model
public class caitlinpRealViewModel
{
public List<SelectListItem> IDList { get; set; }
public string selectedId { get; set; }
public List<SelectListItem> ManagerList { get; set; }
public string selectedManager { get; set; }
}
public class HomeController : Controller
{
public caitlinpRealViewModel SetupViewModel(caitlinpRealViewModel vm)
{
caitlinpRealViewModel viewModel = new caitlinpRealViewModel();
if (vm != null)
{
viewModel.selectedId = vm.selectedId;
}
else
{
viewModel.selectedId = "1";
}
SelectListItem listItem = new SelectListItem() { Text = "1", Value = "1" };
SelectListItem listItem2 = new SelectListItem() { Text = "2", Value = "2" };
List<SelectListItem> list = new List<SelectListItem>();
list.Add(listItem);
list.Add(listItem2);
if (vm != null)
{
viewModel.selectedManager = vm.selectedManager;
}
else
{
viewModel.selectedManager = "1";
}
SelectListItem listItem3 = new SelectListItem() { Text = "aManager", Value = "1" };
SelectListItem listItem4 = new SelectListItem() { Text = "bManager", Value = "2" };
List<SelectListItem> list2 = new List<SelectListItem>();
list2.Add(listItem3);
list2.Add(listItem4);
viewModel.IDList = list;
viewModel.ManagerList = list2;
return viewModel;
}
[HttpPost]
public ActionResult Selection(caitlinpRealViewModel vm)
{
caitlinpRealViewModel viewModel = SetupViewModel(vm);
return View(viewModel);
}
public ActionResult Tut135()
{
caitlinpRealViewModel viewModel = SetupViewModel(null);
return View(viewModel);
}
View 1
#model Testy20161006.Controllers.caitlinpRealViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut135</title>
</head>
<body>
#using (Html.BeginForm("Selection", "Home", FormMethod.Post))
{
<div class="container" id='div_release'>
#Html.DropDownListFor(m => m.selectedId, new SelectList(Model.IDList, "Value", "Text"))
#Html.DropDownListFor(m => m.selectedManager, new SelectList(Model.ManagerList, "Value", "Text"))
<input type="submit" name="Submit" id="btnUploadData" class="btn btn-primary" value="Upload" />
</div>
}
</body>
</html>
View 2 (Selection)
#model Testy20161006.Controllers.caitlinpRealViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Selection</title>
</head>
<body>
<div class="container">
<table id="myTable" align="left">
#using (Html.BeginForm("Selection", "Home", FormMethod.Post))
{
<div class="container" id='div_release'>
#Html.DropDownListFor(m => m.selectedId, new SelectList(Model.IDList, "Value", "Text"))
#Html.DropDownListFor(m => m.selectedManager, new SelectList(Model.ManagerList, "Value", "Text"))
<input type="submit" name="Submit" id="btnUploadData" class="btn btn-primary" value="Submit" />
</div>
}
</table>
</div>
</body>
</html>
Related
I am doing an ASP.NET Framework MVC project and I need to send the combo boxes selected items from below partial view to the server with Jquery Ajax but these combo boxes must be validated at first and then the data must be sent in view model with Ajax to the action (DigestFile(ModelDto Mappings)) in the controller. My project parts is as below :
The partial view as below:
#using Web.Library.Bases;
#inherits Common.DataTransferObjects.Originals.ModelDto
#{
Layout = "";
List<(string Caption, bool IsAsigned, bool IsMandatory, bool IsSelected, string Name, string Title)> dataBaseFields = ViewBag.DataBaseFields;
int counter = 0;
}
<div id="Excel_B" class="editor-block">
#Html.Hidden("IsNotMatched")
<div class="block-label">
<p class="vertical-text">
تناظر فیلدها
</p>
</div>
<div class="block-content">
#foreach (var chlItem in dataBaseFields)
{
<div id="ExcelFields_G" class="editor-group ">
<div id="ExcelFields_L" class="editor-label mandatory">
<span class="MappingLabel">#chlItem.Caption :</span>
</div>
#switch (chlItem.Name)
{
case "RowNumber":
<div id="ExcelFields_A" class="editor-field ">
#Html.EditorFor(model => model.RowNumber, "ComboBox")
#Html.ValidationMessageFor(model => model.RowNumber)
</div>
break;
case "Name":
<div id="ExcelFields_B" class="editor-field ">
#Html.EditorFor(model => model.Name, "ComboBox")
#Html.ValidationMessageFor(model => model.Name)
</div>
break;
case "Family":
<div id="ExcelFields_C" class="editor-field ">
#Html.EditorFor(model => model.Family, "ComboBox")
#Html.ValidationMessageFor(model => model.Family)
</div>
break;
case "Code":
<div id="ExcelFields_D" class="editor-field ">
#Html.EditorFor(model => model.Code, "ComboBox")
#Html.ValidationMessageFor(model => model.Code)
</div>
break;
case "NationalCode":
<div id="ExcelFields_E" class="editor-field ">
#Html.EditorFor(model => model.NationalCode, "ComboBox")
#Html.ValidationMessageFor(model => model.NationalCode)
</div>
break;
default:
break;
}
</div>
}
</div>
#if (Model.IsNotMatched > 0)
{
<div class="DigestBut" title="Read File">
<a href="#" class="submitLink" onclick="DigestButtonClicked()">
Read File
</a>
</div>
}
</div>
</div>
The View Model as below:
namespace Common.DataTransferObjects.Originals
{
public class ModelDto
{
[Display(Name = "RowNumber")]
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
public string RowNumber { set; get; }
[Display(Name = "Name")]
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
public string Name { set; get; }
[Display(Name = "Family")]
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
public string Family { set; get; }
[Display(Name = "Code")]
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
public string Code { set; get; }
[Display(Name = "NationalCode")]
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
public string NationalCode { set; get; }
}
}
The Action is as below:
public ActionResult DigestFile(ModelDto Mappings)
{
....
}
Here is how you have to proceed in case you have many 'entries' to send in same time to save in your controller, but of course you can use it to send only one:
In your view:
<input id="Button1" type="button" value="button" onclick="SaveMe()" />
<script>
function SaveMe() {
// Get the value of your edit
var RowNumber0 = $("#RowNumber").val();
var Name0 = $("#Name").val();
var Family0 = $("#Family").val();
var Code0= $("#Code").val();
var NationalCode0= $("#NationalCode").val();
// Creat Object
var lineItems = new Object();
lineItems.Entrys = new Array();
// Example Filling your object...
lineItems.Entrys[0] = new Object({ RowNumber: RowNumber0, Name: Name0, Family: Family0, Code : Code0, NationalCode: NationalCode0 });
//lineItems.Entrys[1] = ... same logic for your other entries
// send by ajax to your controller and getting answer ...
$.ajax({
type: "POST",
url: "/Home/AjaxMethodDigestFile",
data: JSON.stringify({ Entrys: lineItems.Entrys }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) { alert(response.message); },
failure: function (response) { alert("failure"); },
error: function (response) { alert("error"); }
});
}
in your controller:
[HttpPost]
public JsonResult AjaxMethodDigestFile(ICollection<Common.DataTransferObjects.Originals.ModelDto > Entrys)
{
string message = "";
int counter = 0;
foreach (var entry in Entrys)
{
// How to use this data example
string RowNumber = entry.RowNumber;
string Name= entry.Name;
counter += 1;
message += "Saved " + ": " + counter + Constants.vbCrLf;
}
// The following lines are not necessary, it's just an example code to know what happen and return it to client side ...
if (counter > 0)
message = counter.ToString() + " Entrys received" + Constants.vbCrLf + message;
else
message = "no entrys";
var response = new { counter, message };
return Json(response);
}
EDIT:
About the validation
I don't know the library that you are using FoundationValidationMessages so can't help much with this, but I tried a classic way that work:
In Model:
[Required(ErrorMessage = "Required")]
public string RowNumber { set; get; }
In View:
#using (Html.BeginForm("Test2", "Home", FormMethod.Post))
{
...
#Html.EditorFor(model => model.RowNumber)
#Html.ValidationMessageFor(model => model.RowNumber)
...
}
And in your controller :
[HttpPost]
public ActionResult Test2(ModelDto um)
{
if (ModelState.IsValid)
{
return View(um);
}
else
{
return View();
}
}
I have a view component, EventsViewComponent, which is loaded in my Events view index.cshtml using the following lines of code:
<div id="events">
#await Component.InvokeAsync("Events", new { showPrevious = Model.ShowPrevious, showUpcoming = Model.ShowUpcoming })
</div>
I have two checkboxes added like this:
#Html.CheckBoxFor(m => m.ShowPrevious, new { id = "cbShowPrevious", onchange = "ReloadEvents()" })
#Html.CheckBoxFor(m => m.ShowUpcoming, new { id = "cbShowUpcoming", onchange = "ReloadEvents()" })
ReloadEvents() refers to a Javascript function in which I was hoping to refresh the EventsViewComponent with an Ajax call something like:
function ReloadEvents() {
$.ajax({
url: '#Url.Action("ReloadEvents", "Events")',
data: {
showPrevious: document.getElementById("cbShowPrevious").checked,
showUpcoming: document.getElementById("cbShowUpcoming").checked
},
success: DoThis()
})
}
function DoThis() {
const eventsDiv = document.getElementById('events');
eventsDic.innerHTML = //HTML from EventsViewComponent
}
But I don't seem to be able to get the HTML from the EventsViewComponent.
I have written the Default.cshtml for EventsViewComponent like this:
#{
List<Event> events = ViewData["Events"] as List<Event>;
if (events.Count > 0)
{
<table>
//event data from the model
</table>
}
}
The InvokeAsync method in EventsViewComponent is being hit, as is the ReloadEvents method in EventsController but I'm obviously misunderstanding something as I don't seem to be able to update the EventsViewComponent.
Please could someone advise if this is possible and how to go about achieveing it?
To get the HTML from the EventsViewComponent,you need to change like below:
success: function (data) {
$("#events").html(data);
}
Here is a whole working demo like below:
1.Model:
public class Event
{
public bool ShowPrevious { get; set; }
public bool ShowUpcoming { get; set; }
public string Data { get; set; }
}
2.ViewComponent:
public class EventsViewComponent : ViewComponent
{
List<Event> data = new List<Event>() {
new Event(){ ShowPrevious=true,ShowUpcoming=false,Data="aaa"},
new Event(){ ShowPrevious=false,ShowUpcoming=true,Data="bbb"},
new Event(){ ShowPrevious=false,ShowUpcoming=true,Data="ccc"},
};
public IViewComponentResult Invoke(bool showPrevious,bool showUpcoming)
{
if (showPrevious == true && showUpcoming == true)
{
ViewData["Events"] = data;
}
else if (showPrevious)
{
ViewData["Events"] = data.Where(u => u.ShowPrevious == true).ToList();
}
else if(showUpcoming)
{
ViewData["Events"] = data.Where(u => u.ShowUpcoming == true).ToList();
}
return View();
}
}
3.Controller:
public class HomeController : Controller
{
public IActionResult ReloadEvents(bool showPrevious, bool showUpcoming)
{
return ViewComponent("Events", new { showPrevious = showPrevious, showUpcoming = showUpcoming });
}
public IActionResult Index()
{
var model = new Event() { ShowPrevious = true, ShowUpcoming = true };
return View(model);
}
}
4.Index.cshtml:
#model Event
#Html.CheckBoxFor(m => m.ShowPrevious, new { id = "cbShowPrevious", onchange = "ReloadEvents()" })
#Html.CheckBoxFor(m => m.ShowUpcoming, new { id = "cbShowUpcoming", onchange = "ReloadEvents()" })
<div id="events">
#await Component.InvokeAsync("Events", new { showPrevious = Model.ShowPrevious, showUpcoming = Model.ShowUpcoming })
</div>
#section Scripts
{
<script>
function ReloadEvents() {
$.ajax({
url: '#Url.Action("ReloadEvents", "Home")',
data: {
showPrevious: document.getElementById("cbShowPrevious").checked,
showUpcoming: document.getElementById("cbShowUpcoming").checked
},
success: function (data) {
$("#events").html(data);
}
})
}
</script>
}
5.Default.cshtml(the view component Razor view):
#model Event
#{
List<Event> events = ViewData["Events"] as List<Event>;
if (events.Count > 0)
{
<table>
<tr>
<th>ShowPrevious</th>
<th>ShowUpcoming</th>
<th>Data</th>
</tr>
<tbody>
#foreach (var item in events)
{
<tr>
<td>#item.ShowPrevious</td>
<td>#item.ShowUpcoming</td>
<td>#item.Data</td>
</tr>
}
</tbody>
</table>
}
}
Result:
I have implemented such solution in one of my projects, check it out -> Refreshing .Net core MVC ViewComponent over AJAX
View Code
#using(Html.BeginForm("Edit",
"Products",
FormMethod.Post,
new {
enctype = "multipart/form-data"
})) {
#Html.AntiForgeryToken()
< div class = "form-horizontal" >
#Html.ValidationSummary(true, "", new {
#class = "text-danger"
})
#Html.HiddenFor(model => model.Id)
< div class = "form-group" >
#Html.LabelFor(model => model.Image, htmlAttributes: new {
#class = "control-label col-md-2"
}) < div class = "col-md-10" >
< img src = "#Url.Content(Model.Image)"
width = "150" / >
< /div> < /div>
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Product product, HttpPostedFileBase file) {
if (ModelState.IsValid) {
Product p = new Product {
Id = product.Id,
Name = product.Name,
Description = product.Description,
Image = product.Image
};
if (file != null) {
string Image = Path.Combine(Server.MapPath("~/Upload"), Path.GetFileName(file.FileName));
file.SaveAs(Image);
p.Image = "~/Upload/" + file.FileName;
}
db.Entry(p).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
} else {
return View(product);
}
}
public ActionResult Edit(int ? id) {
if (id == null) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null) {
return HttpNotFound();
}
return View(product);
}
I want to delete the picture with the button. How can I do it ? I can delete products but I can not delete pictures. I can delete products with Id. I tried to do examples on the internet but I could not. Would you make an illustrative example?
Below are some basic setup which should work for you.
Action Methods:
public ActionResult Index()
{
//Adding some dummy product data for example, Usually you will get real details from DB.
List<Product> products = new List<Product>();
Product product1 = new Product()
{
Id = 1,
Name = "Bint Beef",
Description = "Product Bint Beef",
ImageName = "bintbeef-1"
};
Product product2 = new Product()
{
Id = 2,
Name = "Bint Beef 2",
Description = "Product Bint Beef 2",
ImageName = "bintbeef-2"
};
products.Add(product1);
products.Add(product2);
return View(products);
}
[HttpPost]
public ActionResult DeleteProductImage(int productID)
{
try
{
string file_name = Convert.ToString(productID);
//Here you can instead use `ImageName` property to fetch the name from db based
on product id and then delete image
string path = Server.MapPath("~/Content/Images/" + file_name + ".jpg");
FileInfo file = new FileInfo(path);
if (file.Exists)//check file exsit or not
{
file.Delete();
}
return Json(new { status = true }, JsonRequestBehavior.AllowGet);
}
catch
{
return Json(new { status = false }, JsonRequestBehavior.AllowGet);
}
}
Index View
#model IEnumerable<DemoMvc.Models.Product>
<h2>Product List</h2>
<table class="table">
<tr>
<th>
Product Id
</th>
<th>
Name
</th>
<th>
Image Name
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<th>
#item.Id
</th>
<td>
#item.Name
</td>
<td>
#item.ImageName
</td>
<td>
#using (Html.BeginForm("DeleteProductImage", "Home"))
{
<input name="productID" type="hidden" value="#item.Id" />
<button type="submit">Delete Image</button>
}
</td>
</tr>
}
</table>
Reference.
I'm creating event calendar using daypilot lite. I'm following this tutorial to create the application in ASP.NET MVC 5.
When I clicked the calendar, for example 30/04/2015 02:00 PM - 30/04/2015 03:00 PM, the popup form will show up. In popup form, I'm using jquery datepicker and jquery timepicker on start and end field. Here is the picture & code to describe what I've done:
Index.cshtml:
#Html.DayPilotCalendar("dp", new DayPilotCalendarConfig
{
BackendUrl = Url.Action("Backend", "Calendar"),
BusinessBeginsHour = 8,
BusinessEndsHour = 19,
ViewType = ViewType.Day,
TimeRangeSelectedHandling = TimeRangeSelectedHandlingType.JavaScript,
TimeRangeSelectedJavaScript = "create(start, end)",
EventClickHandling = EventClickHandlingType.JavaScript,
EventClickJavaScript = "edit(e)",
EventMoveHandling = EventMoveHandlingType.Notify,
EventResizeHandling = EventResizeHandlingType.Notify,
EventDeleteHandling = EventDeleteHandlingType.CallBack
})
<script type="text/javascript">
function create(start, end) {
var m = new DayPilot.Modal();
m.closed = function () {
if (this.result == "OK") {
dp.commandCallBack('refresh');
}
dp.clearSelection();
};
m.showUrl('#Url.Action("Create", "Event")?start=' + start + '&end=' + end);
}
</script>
Create.cshtml:
#model Calendar.ViewModels.CreateEventViewModel
<link href="#Url.Content("~/Content/jquery-ui.min.css")" rel="stylesheet" />
<script src="#Url.Content("~/Scripts/jquery-2.1.3.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.11.4.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
<link rel="stylesheet" type="text/css" href="#Url.Content("~/Content/jquery.timepicker.css")" />
<script src="#Url.Content("~/Scripts/jquery.timepicker.min.js")"></script>
#using (Html.BeginForm())
{
<fieldset>
<legend>Event Details:</legend>
<table>
<tr>
<td>
<label for="name">Event Name</label>
</td>
<td>
#Html.EditorFor(model => model.name, new { htmlAttributes = new { #class = "ui-widget-content ui-corner-all" } })
#Html.ValidationMessageFor(model => model.name, "", new { #class = "" })
</td>
</tr>
<tr>
<td>
<label for="startdate">Start</label>
</td>
<td>
#Html.EditorFor(model => model.startdate, new { htmlAttributes = new { #class = "ui-widget-content ui-corner-all datepicker", #readonly = "readonly" } })
#Html.EditorFor(model => model.starttime, new { htmlAttributes = new { #class = "ui-widget-content ui-corner-all timepicker" } })
#Html.ValidationMessageFor(model => model.startdate, "", new { #class = "" })
</td>
</tr>
<tr>
<td>
<label for="enddate">End</label>
</td>
<td>
#Html.EditorFor(model => model.enddate, new { htmlAttributes = new { #class = "ui-widget-content ui-corner-all datepicker", #readonly = "readonly" } })
#Html.EditorFor(model => model.endtime, new { htmlAttributes = new { #class = "ui-widget-content ui-corner-all timepicker" } })
#Html.ValidationMessageFor(model => model.enddate, "", new { #class = "" })
</td>
</tr>
</table>
</fieldset>
<br />
<div style="text-align: right">
<button type="submit" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary">Save</button>
Cancel
</div>
}
<script>
$(function () {
$(".datepicker").datepicker({
dateFormat: "dd/mm/yy"
});
$(".timepicker").timepicker({
"forceRoundTime": true,
"timeFormat": "h:i A"
});
$("form").submit(function () {
var f = $("form");
if (f.valid()) {
$.post(f.action, f.serialize(), function (result) {
close(eval(result));
});
}
return false;
});
});
function close(result) {
if (parent && parent.DayPilot && parent.DayPilot.ModalStatic) {
parent.DayPilot.ModalStatic.close(result);
}
}
</script>
CreateEventViewModel.cs
public class CreateEventViewModel
{
[Required]
[StringLength(50)]
public string name { get; set; }
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime startdate { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime starttime { get; set; }
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime enddate { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime endtime { get; set; }
}
If I clicked Save button it always get focus to starttime textbox. I've debugged using F12 Developer Tools there is no error or post action. The problem solved if I'm not using jquery timepicker.
What am I doing wrong?
i think is the DataFormatString in your class, modify it like this:
public class CreateEventViewModel
{
[Required]
[StringLength(50)]
public string name { get; set; }
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime startdate { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:t}")]
public DateTime starttime { get; set; }
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime enddate { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:t}")]
public DateTime endtime { get; set; }
}
i just changed the {0:HH:mm} hour format to {0:t} on starttime and endtime
My guess is that there is an error inside the submit event handler:
$("form").submit(function () {
var f = $("form");
if (f.valid()) {
$.post(f.action, f.serialize(), function (result) {
close(eval(result));
});
}
return false;
});
The error prevents "return false;" from being called which means the form is posted directly instead of using the $.post() call. The browser JS console is usually cleared on POST and that's why you don't see any error.
The actual problem might be that f.serialize() doesn't serialize the value from jQuery date/time pickers properly.
Try wrapping the code with try { ... } catch (e) { ... } to see the error:
$("form").submit(function () {
try {
var f = $("form");
if (f.valid()) {
$.post(f.action, f.serialize(), function (result) {
close(eval(result));
});
}
return false;
}
catch(e) {
alert("Error while processing the form: " + e);
}
});
I will display a view, when I click on checkbox
I tried like this, but not work,
I need your help to fix the problem
Models:
public class DisplayData
{
public bool ID { get; set; }
public DisplayData(bool ID)
{
this.ID = ID;
}
}
public class Element
{
public string Descripcion { get; set; }
}
HomeController:
public ActionResult Index()
{
DisplayData Display = new DisplayData(false);
return View(Display);
}
Index.cshtml:
#model AppTwitter.Models.DisplayData
<script src="#Url.Content("~/Scripts/myCheckbox.js")" type="text/javascript"></script>
#Html.CheckBoxFor(
x => x.ID,
new {
data_url = Url.Action("PartialDemo", "PartialDemo"),
id = "mycheckbox"
}
myCheckbox.js:
$(function () {
$('#mycheckbox').change(function () {
var data = {};
data[$(this).attr('name')] = $(this).is(':checked');
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: data,
success: function (result) {
}
});
});
});
PartialDemoController.cs
public ActionResult PartialDemo()
{
var element = new Element();
element.Descripcion = "Descripcion";
return View(element);
}
PartialDemo.cshtml:
#model AppTwitter.Models.Element
<div class="editor-label">
#Html.LabelFor(model => model.Descripcion )
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Descripcion )
#Html.ValidationMessageFor(model => model.Descripcion )
</div>
Thanks,
#Victor, Now i got the issue. The id that you are assigning to checkbox doesn't get worked because you are using #Html.CheckBoxFor(x => x.ID). in this case the id of checkbox is generating dynamically hence "mycheckbox" doesn't get worked. So Instead assigning a id assign a class i.e
#Html.CheckBoxFor(
x => x.ID,
new {
data_url = Url.Action("PartialDemo", "PartialDemo"),
#class = "mycheckbox"
}
)
and in javascript use below:
$(function () {
$('.mycheckbox').click(function () {
// your existing stuff
});
});
Hope this will solve the problem