Input box as “date” on web when model is “int” (again) - asp.net-mvc

I decided to create a new post here instead of the other post which was a bit confusing. (Input box as "date" on web when model is "int")
In this post I have added the code I use.
The problem is that in the SQL server the field FrDr is of type int and I need the user on the webpage to enter in a input field of type "date"
If I add [DataType(DataType.Date)] to the model i get the input date type autmoatically. but not if I add it to the Page Model
How can I change my code so that the user get an input field of type date that save the date value as an int to SQL.
MODEL AGR.CS
namespace DateTest.VismaModels {
public partial class Agr {
[Key]
[Display(Name = "Actor")]
public int AgrActNo { get; set; }
public int AgrNo { get; set; }
[DataType(DataType.Date)]
[Display(Name = "From Date")]
public int FrDt { get; set; }
}
}
PAGE MODEL
namespace DateTest.Pages {
public class IndexModel : PageModel {
private readonly DateTest.VismaModels.F0001Context _context;
public IndexModel(DateTest.VismaModels.F0001Context context) {
_context = context;
}
public bool ShowMessage => !string.IsNullOrEmpty(Message);
[TempData]
public string Message { get; set; }
[BindProperty]
public Agr AgrRow { get; set; }
public async Task<IActionResult> OnGetAsync(int? id) {
if (id == null) {
Console.WriteLine("New");
AgrRow = new Agr();
AgrRow.AgrNo = _context.Agr.Select(q => q.AgrNo).DefaultIfEmpty(0).Max() + 1;
//AgrRow.FrDt = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
}
if (!ModelState.IsValid) {
//var errors = ModelState.Select(x => x.Value.Errors).Where(y => y.Count > 0).ToList();
var errors = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
Message += "Model not valid : " + errors;
return Redirect("~/Activities/index");
}
return Page();
}
public async Task<IActionResult> OnPostSaveNewRowAsync() {
if (!ModelState.IsValid) {
//var errors = ModelState.Select(x => x.Value.Errors).Where(y => y.Count > 0).ToList();
var errors = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
Message += "Model not valid : " + errors;
return Redirect("~/index");
}
_context.Add(AgrRow);
try {
await _context.SaveChangesAsync();
} catch (DbUpdateConcurrencyException) {
throw;
}
Message += "Saved";
return RedirectToPage("/index");
}
}
}
RAZOR PAGE
#page
#model DateTest.Pages.IndexModel
#{
ViewData["Title"] = "Activities";
}
<h2>Activities</h2>
#if (Model.ShowMessage) {<div class="alert alert-info alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"></button>
#Model.Message
</div>
}
<p>
<a asp-page="Create">Create New</a>
</p>
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="AgrRow.AgrNo" />
<table class="table">
<tbody>
<tr>
<td><input asp-for="#Model.AgrRow.AgrActNo" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.FrDt" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.ToDt" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.FrTm" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.ToTm" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.CustNo" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.ProdNo" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.Descr" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.NoInvoAb" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.Price" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.Am" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.Fin" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.Invo" class="form-control" /></td>
<td>
<div class="form-group">
<button type="submit" value="Save New" asp-page-handler="saveNewRow" asp-route-id="#Model.AgrRow.AgrNo" class="btn btn-default">
<i class="fa fa-save"></i>Create
</button>
</div>
</td>
</tr>
</tbody>
</table>
</form>
UPDATE
If I add the following to the Page Model
public DateTime FrDt { get; set; }
And print out the result in the post method like this
Console.WriteLine("FRDT = " + FrDt);
Console.WriteLine("AGRROW FRDT = " + AgrRow.FrDt);
I get this
FRDT = 0001-01-01 00:00:00
AGRROW FRDT = 0

I figured it out.
In my Agr Model I add a temporary field FrDt2 which is of DateTime and use the [NotMapped] annotation so it does not send it to sql
[NotMapped]
public DateTime FrDt2 { get; set; }
And in my Page model I convert FrDt2 to int before adding it to FrDt.
AgrRow.FrDt = int.Parse(AgrRow.FrDt2.ToString("yyyyMMdd"));
And, to show an existing item from SQL in the input date box I convert it back to int like this
AgrRow.FrDt2 = DateTime.ParseExact(AgrRow.FrDt.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);

Related

Unable to process binding "event: function(){return {change:flagSalesOrderItemAsEdited} }"

I am currently doing a Pluralsight course on Knockout and MVC (called Parent-Child Data with EF, MVC, Knockout, Ajax, and Validation) which I have been very impressed with, but suddenly I get this bug which has so far been a show stopper for me.
Not only is it a problem in my code, it is also a bug in the very code downloaded from Pluralsight that I saw working on their video!
So in the Edit Partial View I have:
<h2>#ViewBag.Title</h2>
<p data-bind="text: MessageToClient"></p>
<div>
<div class="form-group">
<label class="control-label" for="CustomerName">Customer Name:</label>
<input class="form-control" name="CustomerName" id="CustomerName"
data-bind="value: CustomerName, event: {change: flagSalesOrderAsEdited}"/>
</div>
<div class="form-group">
<label class="control-label" for="PONumber">P.O. Number:</label>
<input class="form-control" name="PONumber" id="PONumber"
data-bind="value: PONumber, event: {change: flagSalesOrderAsEdited}"/>
</div>
</div>
<table class="table table-stripe">
<tr>
<th>Product Code</th>
<th>Quantity</th>
<th>Unit Price</th>
<th><button data-bind="click: addSalesOrderItem" class="btn btn-info btn-xs">Add</button></th>
</tr>
<tbody data-bind="foreach: SalesOrderItems">
<tr>
<td class="form-group">
<input class="form-control input-sm"
data-bind="value: ProductCode, event: {change: flagSalesOrderItemAsEdited}, hasfocus: true" />
</td>
<td class="form-group">
<input class="form-control input-sm"
data-bind="value: Quantity, event: {change: flagSalesOrderItemAsEdited}" />
</td>
<td class="form-group">
<input class="form-control input-sm"
data-bind="value: UnitPrice, event: {change: flagSalesOrderItemAsEdited}" />
</td>
<td class="form-group">Delete</td>
</tr>
</tbody>
</table>
<p><button data-bind="click: save" class="btn btn-primary">Save</button></p>
<p>
« Back to List
</p>
and I apply bindings;
<script type="text/javascript">
var salesOrderViewModel = new SalesOrderViewModel(#Html.Raw(data));
ko.applyBindings(salesOrderViewModel);
</script>
In my javascript file I have
var ObjectState = {
Unchanged: 0,
Added: 1,
Modified: 2,
Deleted: 3
};
var salesOrderItemMapping = {
'SalesOrderItems': {
key: function(salesOrderItem) {
return ko.utils.unwrapObservable(salesOrderItem.salesOrderItemId);
},
create: function(options) {
return new SalesOrderViewModel(options.data);
}
}
};
SalesOrderItemViewModel = function(data) {
var self = this;
ko.mapping.fromJS(data, salesOrderItemMapping, self);
self.flagSalesOrderItemAsEdited = function() {
if (self.ObjectState() !== ObjectState.Added) {
self.ObjectState(ObjectState.Modified);
}
return true;
};
}
SalesOrderViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, salesOrderItemMapping, self);
self.save = function() {
$.ajax({
url: "/Sales/Save",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json",
success: function (data) {
if (data.salesOrderViewModel !== null) {
ko.mapping.fromJS(data.salesOrderViewModel, {}, self);
}
if (data.newLocation !== undefined && data.newLocation !== null) {
window.location.href = data.newLocation;
}
}
});
}
self.flagSalesOrderAsEdited = function () {
if (self.ObjectState() !== ObjectState.Added) {
self.ObjectState(ObjectState.Modified);
}
return true;
}
The mappings are derived from the server side viewModels:
namespace SolutionName.Web.ViewModels
{
public class SalesOrderViewModel : IObjectWithState
{
public SalesOrderViewModel()
{
this.SalesOrderItems = new ListStack<SalesOrderItemViewModel>();
}
public int SalesOrderId { get; set; }
public string CustomerName { get; set; }
public string PONumber { get; set; }
public string MessageToClient { get; set; }
public ObjectState ObjectState { get; set; }
public List<SalesOrderItemViewModel> SalesOrderItems { get; set; }
}
}
and
namespace SolutionName.Web.ViewModels
{
public class SalesOrderItemViewModel : IObjectWithState
{
public int SalesOrderItemId { get; set; }
public string ProductCode { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public int SalesOrderId { get; set; }
public ObjectState ObjectState { get; set; }
}
}
The error occurs in the table where I have data-binded the flag field:
<td class="form-group">
<input class="form-control input-sm"
data-bind="value: ProductCode, event: {change: flagSalesOrderItemAsEdited}, hasfocus: true" />
</td>
I get 'flagSalesOrderItemAsEdited' is undefined
And it falls over the in the knockout script.
Unable to process binding "foreach: function(){return SalesOrderItems }"
Message: Unable to process binding "event: function(){return {change:flagSalesOrderItemAsEdited} }"
Message: 'flagSalesOrderItemAsEdited' is undefined
ex.message = "Unable to process binding \"" + bindingKey + ": " + bindings[bindingKey] + "\"\nMessage: " + ex.message;
Line 3326 Exception
So how do I fix this?
EDIT
One suggested solution is to use $parent as a prefix in the HTML.
So I tried:
<td class="form-group">
<input class="form-control input-sm"
data-bind="value: ProductCode, event: {change: $parent.flagSalesOrderItemAsEdited}, hasfocus: true" />
</td>
<td class="form-group">
<input class="form-control input-sm"
data-bind="value: Quantity, event: {change: $parent.flagSalesOrderItemAsEdited}" />
</td>
<td class="form-group">
<input class="form-control input-sm"
data-bind="value: UnitPrice, event: {change: $parent.flagSalesOrderItemAsEdited}" />
</td>
This stopped the exception being thrown. However the method:
self.flagSalesOrderAsEdited = function () {
if (self.ObjectState() !== ObjectState.Added) {
self.ObjectState(ObjectState.Modified);
}
was NOT invoked. It was as though the class it is in was not instantiated.
try the following.use $root while calling a function inside a loop
<td class="form-group">
<input class="form-control input-sm"
data-bind="value: ProductCode, event: {change: $root.flagSalesOrderItemAsEdited}, hasfocus: true" />
</td>
We can also use $parent which is the immeditely outside the current context.
More info on binding context

How to get client side generated class list to MVC post action argument?

I have one form where I am generating some control dynamically (Which is list some class . in image add product artwork section) When I click on submit button how can i get this values in post Action method's argument so that I can use this value in collection.
For reference I have attached the image where i have option for multiple Artwork oprion
[HttpPost]
public ActionResult Add(Graphic graphicToAdd,Enumerable<GraphicArtwork> artworkOption)
{
// I want value in artworkOption
}
public class GraphicArtwork
{
[Key]
public int GraphicArtworkId { get; set; }
public int GraphisId { get; set; }
[Required(ErrorMessage = "The {0} is required.")]
[DisplayName("Option Text")]
[StringLength(500)]
public string ArtOptionText { get; set; }
public decimal Price { get; set; }
[DisplayName("Active")]
public bool IsActive { get; set; }
public DateTime CreatedDate { get; set; }
[NotMapped]
public int TotalRecordCount { get; set; }
}
This is my view :
<div class="editor-field PrintOptions">
<table data-bind="visible :customArtworks().length > 0">
<thead>
<tr>
<td class="editor-label">Option</td>
<td class="editor-label">Price</td>
<td></td>
</tr>
</thead>
<tbody data-bind="foreach: customArtworks">
<tr>
<td>
<input placeholder="Enter Artwork Text" type="text" data-bind="value: ArtOptionText'}" />
</td>
<td>
<input placeholder="Enter Price" type="text" data-bind="value: Price" />
</td>
<td>
<img title="Add" src="~/Content/images/icon_add.png">
<img title="Delete" style="margin-left:10px;" src="~/Content/images/icon_delete.png">
</td>
</tr>
</tbody>
</table>
</div>
For more detail : I am generating my dynamical control using knockout.js
// Ko Implemntation
function GraphicArtwork(ArtOptionText, Price) {
var self = this;
self.ArtOptionText = ArtOptionText;
self.Price = Price;
self.formattedPrice = ko.computed(function () {
var price = self.Price;
return price ? "$" + price.toFixed(2) : "0.00";
})
}
function GraphicArtworkViewModel() {
var self = this;
self.customArtworks = ko.observableArray([GraphicArtwork(null, null)]);
self.add = function () {
self.customArtworks.push(new GraphicArtwork(null, null));
};
self.remove = function (GraphicArtwork) {
self.customArtworks.remove(GraphicArtwork);
};
}
ko.applyBindings(new GraphicArtworkViewModel());
Add This binding :
<td>
<input placeholder="Enter Artwork Text" type="text" data-bind="value: ArtOptionText,attr:{name: '['+$index()+'].ArtOptionText'}" />
</td>
<td>
<input placeholder="Enter Price" type="text" data-bind="value: Price,attr:{name: '['+$index()+'].Price'}" />
</td>
AND in Code Behind
public ActionResult Add(Graphic graphicToAdd,IEnumerable<GraphicArtwork> listOfGraphicArtwork)
{
// listOfGraphicArtwork will hold all the required data
}

Mvc HttpPostedFileBase returns null

lately i was trying to handle HttpPostedFileBase returns null issue, but i cannot really figure it out why my input file returns null although i've researched all the similiar questions to get to know about the problem in the site.My sutiation is i need to have four input file because i need four different documents other than each other.
here is part of the view:
#using (Html.BeginForm("Create", "MyController", FormMethod.Post, new { enctype ="multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div style="padding-left: 32px;">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Id)
<table>
<tbody>
<tr>
<td style="width: 132px;"><div><b>...</b></div></td>
<td style="width:250px;">
<input type="file" name="upload1" id="upload1" class="formin" />
<input type="hidden" name="UploadType1" id="UploadType1" value="#Request.QueryString["UploadType"]" />
</td>
</tr>
<tr>
<td style="width: 132px;"><div><b>...</b></div></td>
<td style="width:250px;">
<input type="file" name="upload2" id="upload2" class="formin" />
<input type="hidden" name="UploadType2" id="UploadType2" value="#Request.QueryString["UploadType"]" />
</td>
</tr>
<tr>
<td style="width: 132px;"><div><b>...</b></div></td>
<td style="width:250px;">
<input type="file" name="upload3" id="upload3" class="formin" />
<input type="hidden" name="UploadType3" id="UploadType3" value="#Request.QueryString["UploadType"]" />
</td>
</tr>
<tr>
<td style="width: 132px;"><div><b>...</b></div></td>
<td style="width:250px;">
<input type="file" name="upload4" id="upload4" class="formin" />
<input type="hidden" name="UploadType4" id="UploadType4" value="#Request.QueryString["UploadType"]" />
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td style="width:220px;"><div><b></b></div></td>
<td> <input type="submit" name="submit" value="GÖNDER" class="formbutton" style="font-size: 14px;background:maroon;color:white;"></td>
</tr>
</tbody>
</table>
here is my controller:
[HttpPost]
public ActionResult Create(HttpPostedFileBase upload1, HttpPostedFileBase upload2, HttpPostedFileBase upload3, HttpPostedFileBase upload4, string UploadType1, string UploadType2, string UploadType3, string UploadType4)
{
List<Ek> eks = new List<Ek>();
if (upload1!=null && upload1.ContentLength > 0)
{
var upload1Name= Path.GetFileName(upload1Name.FileName);
var path1 = Path.Combine(Server.MapPath("~/Documents/.../upload1"), PhotoName);
upload1.SaveAs(path1);
Ek e1 = new Ek {
UploadType = GetTypeEnum(UploadType1),
UploadPath = "/Documents/.../.../" + upload1Name
};
eks.Add(e1);
}
if (upload2!= null && upload2.ContentLength > 0)
{
var upload2Name = Path.GetFileName(upload2.FileName);
var path2 = Path.Combine(Server.MapPath("~/Documents/.../..."), upload2Name);
upload2.SaveAs(path2);
Ek e2 = new Ek
{
UploadType = GetTypeEnum(UploadType1),
UploadPath = "/Documents/.../.../" + upload2Name
};
eks.Add(e2);
}
if (upload3!= null && upload3.ContentLength > 0)
{
var upload3Name = Path.GetFileName(upload3.FileName);
var path3 = Path.Combine(Server.MapPath("~/Documents/.../..."), upload3Name );
upload3.SaveAs(path3);
Ek e3 = new Ek
{
UploadType = GetTypeEnum(UploadType1),
UploadPath = "/Documents/.../" + upload3Name
};
eks.Add(e3);
}
if (upload4!= null && upload4.ContentLength > 0)
{
var upload4Name = Path.GetFileName(upload4.FileName);
var path4 = Path.Combine(Server.MapPath("~/Documents/.../"), upload4Name);
languagepoint.SaveAs(path4);
Ek e4 = new Ek
{
UploadType = GetTypeEnum(UploadType1),
UploadPath = "/Documents/.../" + upload4Name
};
eks.Add(e4);
}
//some stuff here
return RedirectToAction("Success");
}
return View(myview);
}
private UploadType GetTypeEnum(string UploadType1)
{
Models.UploadType uType= UploadType.MyType;
switch (UploadType1)
{
case "MyType":
uType = UploadType.MyType;
break;
case "MyType1":
uType = UploadType.MyType1;
break;
case "MyType2":
uType = UploadType.MyType2;
break;
case "MyType3":
uType = UploadType.MyType3;
break;
default:
break;
}
return uType;
}
and finally here is my modal:
public partial class MyMainClass
{
public int Id { get; set; }
public virtual IList<Ek> Ek { get; set; }
}
public partial class Ek
{
public int ID { get; set; }
public UploadType UploadType { get; set; }
public string UploadPath { get; set; }
}
public enum UploadType
{
MyType= 0,
MyType1= 1,
MyType2= 2,
MyType3= 3
}
Thank you for all the answers.
Just Correct Your HttpPost Controller as :
[HttpPost]
public ActionResult Create(IEnumerable<HttpPostedFileBase> files)
{
if (files.Count() > 0) // display no of files uploaded
if (files.Any()) // display true
if (files.First() == null) // display "first null"
return View();
}
Because you are uploading more than one file from view so you have to use IEnumerable of HttpPostedFileBase and write HttpPost attribute on Create action because it is accepting your POST Request.

How to upload form contents with a file to database?

This is my code,i have also tried strongly typed view but i it does not create an upload field
#Model
namespace master_layout.Models
{
[Table("Candidates")]
public class Candidate
{
[Key]
public int CandidateID { get; set; }
public string FirstName { get; set; }
public string LastName{get;set;}
public DateTime Date{get;set;}
public string EmailID{get;set;}
public long ContactNumber{get;set;}
public long AlternateContactNumber{get;set;}
public int RecruitmentStatusID{get;set;}
public DateTime CreatedOn{get;set;}
public DateTime LastUpdatedOn{get;set;}
public byte[] Resume { get; set; }
}
public class CandidateContext : DbContext
{
public DbSet<Candidate> Candidates { get; set; }
}
The following is my controller code
Controller:
namespace proedit1.Controllers
{
public class HomeController : Controller
{
CandidateContext db = new CandidateContext();
public ActionResult Index()
{
return View(db.Candidates.ToList());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Candidate candidate)
{
if (ModelState.IsValid)
{
db.Candidates.Add(candidate);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(candidate);
}
}
}
View:
#using (Html.BeginForm("Newcandidate", "CandidatesController", FormMethod.Post, new { EncType="multipart/form-data"}))
{
<table class="navbar-form">
<tr>
<th>First Name<input type="text" placeholder="Your First Name" class="margin"/></th>
</tr>
<tr>
<th>Last Name<input type="text" placeholder="Your Last Name"/></th>
</tr>
<tr>
<th>Date of Birth <input type="date" name="db" /></th>
</tr>
<tr>
<th>E-Mail ID<input type="email" placeholder="abc#yourserviceprovider.com" /></th>
</tr>
<tr>
<th>Contact No<input type="tel" placeholder="04426506555 or 98414981414" min="8" maxlength="10"/></th>
<tr>
<tr>
<th>Alternate No <input type="tel" placeholder="04426506555 or 98414981414" min="8" maxlength="10"/></th>
<tr>
<th>Created On <input type="date" /></th>
<tr>
<th>Updated On <input type="date" /></th>
</tr>
<tr>
<th> <input type="file" placeholder="your resume in ms.word format" accept="application/msword" name="NamebtnUpload"/>
</th></tr>
</table>
<div class="row">
<div class="span4">
<input type="submit" class="btn-success" value="UPLOAD" name="Submit"/>
<input type="reset" class="btn-warning" name="Reset" />
</div>
</div>
}
I am a newbie in MVC pls provide me with the correct code to upload details to my database
There is a solution which are you looking for:
MVC 4 Razor File Upload
Create new view model for your 'view'. Don't use entity model, please.

When i set value of elements in editor template for grid pop up create , posting to controller as null

in my view there are two grid. when i select a row in first grid, second one is binding according to first one.
what i want to do is take common parameters from first one, used in second one create template in readonly or disabled inputs. my problem is input elements take parameter from first grid but, dont post to controller.
Controller Function
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult DonemKursSinifiOlustur([DataSourceRequest] DataSourceRequest request, DonemKursSinifi model,string DonemId, string DersId, string EgitmenId )
{
if (model != null && ModelState.IsValid)
{
Helper.Islemci.DonemKursSinifiTanimla(model);
}
return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}
model.DonemId, model.DersId, model.EgitmenId and DonemId, DersId, EgitmenId come null.
EditorTemplate View for Grid Create and Update
#model Kurslar.Models.DonemKursSinifi
#using (Html.BeginForm("DonemKursSinifiOlustur","Tanim",FormMethod.Post))
{
<table>
<tr>
<td>
Lütfen Gün ve Saati Belirtiniz:
</td>
<td>
#Html.Kendo().AutoCompleteFor(m=>m.Tanim)
</td>
</tr>
<tr>
<td>
Donem :
</td>
<td>
#Html.Kendo().AutoCompleteFor(m=>m.DonemBaslangicBitis)
#Html.HiddenFor(m => m.DonemId)
</td>
</tr>
<tr>
<td>
Ders Adı:
</td>
<td>
#Html.Kendo().AutoCompleteFor(m=>m.DersAdi)
#Html.HiddenFor(m => m.DersId)
</td>
</tr>
<tr>
<td>
Eğitmen
</td>
<td>
#Html.Kendo().AutoCompleteFor(m=>m.EgitmenAdiSoyadi)
#Html.HiddenFor(m => m.DonemId)
</td>
</tr>
</table>}
First AutoCompleteFor works correctly because take input from user, not before setted.
*and my javaScript code to fill parameters to EditorTemplate *
and it works fine
var grid = $("#donemGrid").data("kendoGrid");
var rows = grid.select();
alert(rows);
try {
var donemID = grid.dataItem(rows).DonemId;
var dersID = grid.dataItem(rows).DersId;
var egitmenID = grid.dataItem(rows).EgitmenId;
var dersAdi = grid.dataItem(rows).DersAdi;
var egitmenAdiSoyadi= grid.dataItem(rows).EgitmenAdiSoyadi;
var donemBaslangicBitis = grid.dataItem(rows).DonemBaslangicBitis;
} catch (e) {
alert(e);
}
$("#DonemBaslangicBitis").data("kendoAutoComplete").value(donemBaslangicBitis);
$("#DersAdi").data("kendoAutoComplete").value(dersAdi);
$("#EgitmenAdiSoyadi").data("kendoAutoComplete").value(egitmenAdiSoyadi);
$("#DonemId").val(donemID);
$("#DersId").val(dersID);
$("#EgitmenId").val(egitmenID);
*if needed, my model *
public class DonemKursSinifi
{
[Key]
[Required]
[PersistentProperty(IsAutoIncremented = true)]
public int Id { get; set; }
[PersistentProperty]
public string Tanim { get; set; }
[PersistentProperty]
public int DonemId { get; set; }
[PersistentProperty]
public int DersId { get; set; }
[PersistentProperty]
public int EgitmenId { get; set; }
[PersistentProperty]
public int KontenjanSayisi { get; set; }
[PersistentProperty]
public int TarifeId { get; set; }
[PersistentProperty]
public int IslemNo { get; set; } // default 1
public string EgitmenAdiSoyadi { get; set; }
public string DersAdi { get; set; }
public string DonemBaslangicBitis { get; set; }
}
ok, probably you have repeated the id in the grid and also have the same name attributes in the same form to do this:
#Html.HiddenFor(m => m.DersId)
mabe you can do somethin like this:
form:
#model Kurslar.Models.DonemKursSinifi
#using (Html.BeginForm("DonemKursSinifiOlustur","Tanim", FormMethod.Post, new { id="myform"}))
{
<input type="hidden" value="" name="Tanim" />
<input type="hidden" value="" name="DonemBaslangicBitis" />
<input type="hidden" value="" name="DonemId" />
<input type="hidden" value="" name="DersAdi" />
<input type="hidden" value="" name="DersId" />
<input type="hidden" value="" name="EgitmenAdiSoyadi" />
<input type="hidden" value="" name="DonemId" />
}
table:
<table>
<tr>
<td>Lütfen Gün ve Saati Belirtiniz:</td>
<td>#Html.Kendo().AutoCompleteFor(m=>m.Tanim)</td>
</tr>
<tr>
<td>Donem :</td>
<td>#Html.Kendo().AutoCompleteFor(m=>m.DonemBaslangicBitis) #Html.HiddenFor(m => m.DonemId)</td>
</tr>
<tr>
<td>Ders Adı:</td>
<td>#Html.Kendo().AutoCompleteFor(m=>m.DersAdi) #Html.HiddenFor(m => m.DersId)</td>
</tr>
<tr>
<td>Eğitmen</td>
<td>#Html.Kendo().AutoCompleteFor(m=>m.EgitmenAdiSoyadi) #Html.HiddenFor(m => m.DonemId)</td>
</tr>
</table>
js:
var
grid = $("#donemGrid").data("kendoGrid"),
rows = grid.select(),
form = $('#myform');
form.find('input[name="DonemBaslangicBitis"]').val(grid.dataItem(rows).DonemBaslangicBitis);
form.find('input[name="DersAdi"]').val(grid.dataItem(rows).DersAdi);
form.find('input[name="EgitmenAdiSoyadi"]').val(grid.dataItem(rows).EgitmenAdiSoyadi);
form.find('input[name="DonemId"]').val(grid.dataItem(rows).DonemId);
form.find('input[name="DersId"]').val(grid.dataItem(rows).DersId);
form.find('input[name="EgitmenId"]').val(grid.dataItem(rows).EgitmenId);
form.submit();

Resources