This is our Home Index:
#model ELearning.Data.ELearningEgitimDTO
#{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
#if (TempData["message"] != null)
{
<div class="alert alert-info" role="alert">#TempData["message"]</div>
}
<div>
<div>
#if (Model.EgitimTuru == 5)
{
<h1>Yangın Eğitimi</h1>
}
<table class="table table-responsive">
<tr>
<td width="20%">Şirket Adı:</td>
<td width="80%">#Model.Name</td>
</tr>
<tr>
<td>Eğitimi Veren:</td>
<td>#Model.PersonelAdi</td>
</tr>
<tr>
<td>Eğitim Tarihi:</td>
<td>#Model.Tarih</td>
</tr>
</table>
</div>
<div>
<table class="table table-responsive">
<tr>
<td>Eğitim Konuları:</td>
</tr>
#foreach (var konu in Model.Adi)
{
<tr>
<td><ul><li>#konu</li></ul></td>
</tr>
}
</table>
</div>
</div>
<p class="text-right"><button onclick="getStartDate()" class="btn btn-primary btn-lg ">Eğitime Başla »</button></p>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function getStartDate() {
$.post("/Video/GetStartDate",
{
PerNr: #Model.PerNr,
StartDate: "",
EndDate: "",
EgitimFilesId: #Model.FileId
});
}
</script>
</div>
This is Video Index:
#model WebApplication3.Models.VideoLogsModel
#{
ViewBag.Title = "Video Page";
}
<div class="jumbotron">
<div>Eğitime başlanan zaman:</div>
<div id="startdate"></div>
<div class="col-md-12 text-center">
<video controls controlslist="nodownload" id="videoPlayer" width: 100% height: auto>
<source src="~/Video/GetVideo" type="video/mp4">
</video>
</div>
<br />
<div class="text-right">
<p id="button" onclick="egitimiBitir()" class="btn btn-danger btn-lg ">Eğitimi Bitir</p>
</div>
<script type="text/javascript">
var vid = document.getElementById("videoPlayer");
var button = document.getElementById("button");
if (vid.played) {
setInterval(function () { vid.pause(); }, 30000);
}
vid.addEventListener("ended", function() {
button.className = "btn btn-success btn-lg "
});
function egitimiBitir() {
if (vid.ended) {
$.post("/Video/GetEndDate",
{
PerNr: #Model.PerNr,
StartDate= "",
EndDate: "",
EgitimFile sId: #Model.EgitimFilesId
});
}
else {
document.getElementById("message").innerHTML = "Video tamamlanmadan eğitimi bitiremezsiniz.."
}
}
</script>
</div>
This is our main model:
public class ELearningEgitimDTO
{
public ELearningEgitimDTO() { }
public ELearningEgitimDTO(string PerNr, int ID)
{
this.ID = ID;
this.PerNr = PerNr;
}
public int ID { get; set; }
public string PerNr { get; set; }//katılımcıID
public string Name { get; set; }//şirket adı
public int EgitimTuru { get; set; }
public DateTime Tarih { get; set; }//egitim tarihi
public string PersonelAdi { get; set; } // eğitimi veren
public int FileId { get; set; }
public string FileName { get; set; }
public string[] Adi { get; set; }
}
This is our model:
public class VideoLogsModel
{
public int EgitimFilesId { get; set; }
public int PerNr { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
This is our Home Controller:
public class HomeController : Controller
{
public ActionResult Index(int EgitimId=4, string PerNr="2")
{
ELearningService service = new ELearningService();
ELearningEgitimDTO egitim = new ELearningEgitimDTO(PerNr, EgitimId);
return View(service.getInfo(egitim)); //eğitim bilgileri istenirken egitimId ve egitim kullanıcıdaki eğitmenin perNr si verilmeli!!
}
}
This is our Video Controller:
public class VideoController : Controller
{
public ActionResult Index(VideoLogsModel model)
{
return View(model);
}
public ActionResult GetVideo()
{
var memoryStream = new MemoryStream(System.IO.File.ReadAllBytes(#"C:\Users\cyare\Desktop\videoplayback.mp4"));
//byte[] bytes = System.IO.File.ReadAllBytes(#"C:\Users\melik.DESKTOP-LQQAB68\Desktop\videoplayback.mp4");
//System.IO.File.WriteAllBytes(#"C:\Users\melik.DESKTOP-LQQAB68\Desktop\videoplayback.mp4", bytes);
return new FileStreamResult(memoryStream, "video/mp4");
}
/* [HttpPost]
public ActionResult GetStartEndDate(VideoLogsModel logs)
{
DateTime startDate = logs.StartDate; //database de uygun tabloya yazılır
return RedirectToAction("Index", "Video");
}*/
[HttpPost]
public ActionResult GetStartDate(VideoLogsModel model)
{
model.StartDate = System.DateTime.Now;
ELearningDosyaKullaniciDTO user = new ELearningDosyaKullaniciDTO();
user.egitimFileID = model.EgitimFilesId;
user.egitimKullanıcı = model.PerNr;
user.startDate = model.StartDate;
ELearningService service = new ELearningService();
//service.CreateLogs(user);
//return RedirectToAction("Index","Video",model);*/
return RedirectToAction("Index", model);
}
[HttpPost]
public ActionResult GetEndDate(VideoLogsModel model)
{
model.EndDate = System.DateTime.Now;
ELearningDosyaKullaniciDTO user = new ELearningDosyaKullaniciDTO();
user.egitimFileID = model.EgitimFilesId;
user.egitimKullanıcı = model.PerNr;
user.endDate = model.EndDate;
ELearningService service = new ELearningService();
service.UpdateLogs(user);
TempData.Add("message", String.Format("Eğitiminiz Tamamlanmıştır!"));
return RedirectToAction("Index", "Home");
}
}
My question is how can i pass the model from home index to video controller and then to video index?
Video Index doesn't run. It goes to video index but then it runs home index again.
Also it runs egitimibitir() function before button's onclick function.
You send an ajax request to your service. (endpoint => GetEndDate) I think you can change your code like that,
$.ajax({
type: "POST",
url: "/Video/GetEndDate", //your reqeust url
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
// your data here
}),
success: function (data) {
// check state of data
// after check window.location = // redirect url
},
error: function (data) {
// handle exception
}
});
You can change your controller method to a data controller. (not an ActionResult. create a custom result object which include your data and your success state. you can use this custom result object every ajax requests for return state and data). If an exception occurs while executing "GetEndDate" method, you need to handle exception and you need to show it to client. You send exception or your success complete response to to client(view). (you can handle your exception data in ajax error: function)
Related
I want to create a Quiz website with Asp. I want to create Quiz, add questions to the quiz, and add answers to the question. Add question button adds a question, but the Addanswer button submits the form instead of adding an answer to the question.
My classes:
public class Answer
{
[Key]
public Guid Id { get; } = Guid.NewGuid();
public string Content { get; set; }
public Guid QuestionId { get; set; }
public class Question
{
[Key]
public Guid Id { get; } = Guid.NewGuid();
public string Content { get; set; }
public Guid QuizId { get; set; }
public ICollection<Answer> Answers { get; set; } = new List<Answer>() {
new Answer() { Content = "Answeeeer" },
new Answer() { Content = "Answeeeer2" },
new Answer() { Content = "Answeeeer3" }
};
public class Quiz
{
[Key]
public Guid Id { get; } = Guid.NewGuid();
public string Name { get; set; }
public ICollection<Question> Questions { get; set; } = new List<Question>() { };
In front side I have Question and Answer Partial views:
Question Partial View:
#model QuizIt_Tests.Entities.Question
<hr style="height: 4px; color: black;" />
<div class="w-100 p-3 px-5 my-3">
<label asp-for="Content" class="control-label">Question</label>
<input asp-for="Content" class="form-control" value="#Model.Content" />
<span asp-validation-for="Content" class="text-danger"></span>
<div id="answerRows #Model.Id" class="w-75">
#Html.EditorFor(model => model.Answers)
<button class="btn btn-primary" id="addAnswer #Model.Id">Add Answer</button>
</div>
</div>
#section Scripts {
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="jquery-3.6.1.min.js"></script>
<script>
$("#addAnswer " + #Model.Id).click(function () {
console.log("clicked");
$.ajax({
url: '#Url.Action("AddBlankQuestion", "Quizes")',
cache: false,
success: function (html) {
$("#answerRows " + #Model.Id").append(html); },
error: function (xhr, status, error) {
console.log(xhr.responseText);
}
});
return false;
});
</script>
}
Answer Partial View:
#model QuizIt_Tests.Entities.Answer
<div class="row" style="background-color:red; margin: 20px;">
<label asp-for="Content" class="control-label">Answer Content</label>
<input asp-for="Content" class="form-control" value="#Model.Content" />
<span asp-validation-for="Content" class="text-danger"></span>
</div>
My Controller:
public class QuizesController : Controller
{
private readonly ApplicationDBContext _context;
public QuizesController(ApplicationDBContext context)
{
_context = context;
}
public IActionResult AddBlankQuestion(Quiz model)
{
Question question = new Question();
return PartialView("EditorTemplates/Question", question);
}
public IActionResult AddBlankAnswer(Question model)
{
return PartialView("EditorTemplates/Answer", new Answer() { QuestionId = model.Id });
}
}
You did not specify the type attribute in the button, which by default is equal to submit which causes the form to be submitted, to change its behavior, change the type value to button as follows.
<button type="button" class="btn btn-primary" id="addAnswer #Model.Id">Add Answer</button>
So I would like to know how I could have a dynamic list inside a dynamic list, that uses an editorfor form to add items dynamically. I used this blog to add items dynamically:
https://dev.to/stevcooo/add-items-dynamically-in-list-in-net-core-40i9
Below is my order model
''''
public class Order
{
[Key]
public int OrderId { get; set; }
[Required]
[StringLength(100)]
[Display(Name = "Cashier Name")]
public string CashierName { get; set; }
[Display(Name = "Invoice Number")]
public string InvoiceNumber { get; set; }
[Display(Name = "Date Created")]
public DateTime CreatedDate { get; set; }
public List<OrderItem> Items { get; set; }
'''
Below is my OrderItem Model
'''
public class OrderItem
{
[Key]
public int Id { get; set; }
public string ProductName { get; set; }
public string ItemCode { get; set; }
[Range(1, int.MaxValue, ErrorMessage = "Please enter a value bigger than 0")]
public int Quantity { get; set; }
public List<PalletItems> PalletItems { get; set; }
'''
And below is my PalletItems model
'''
public class PalletItems
{
[Key]
public int id { get; set; }
[StringLength(100)]
[Display(Name = "Pallet Number")]
public string PalletNumber { get; set; }
[Display(Name = "Pallet Quantity")]
[Range(1, int.MaxValue, ErrorMessage = "Please enter a value bigger than 0")]
public int Pallet_Quantity { get; set; }
'''
Below is my code for the Order create form that contains the editorfor:
'''
<div id="orderItemsContainer">
#Html.EditorFor(model => model.Items, new { #style = "border:0.2rem" })
<br /><span style="color:red;">#ViewBag.ErrorMessage</span>
</div>
<div class="row">
<div class="col-md-4">
<input class="btn btn-default" type="button" id="btnAdd" value="Add product" />
</div>
<div class="col-md-2">
<input class="btn btn-default" type="button" id="btnRemove" value="Remove product" />
</div>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$("#btnAdd").on('click', function () {
$.ajax({
async: true,
data: $('#form').serialize(),
type: "POST",
url: '/Orders/AddOrderItem',
success: function (partialView) {
console.log("partialView: " + partialView);
$('#orderItemsContainer').html(partialView);
}
});
});
}
'''
Below is my editorfor templates for my OrderItems:
'''
model UserManagement.MVC.Models.OrderItem
<div class="row">
<div class="col-md-4">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
#if (User.IsInRole("Dispatcher"))
{
<div class="form-group">
<label asp-for="ItemCode" class="control-label"></label>
<input asp-for="ItemCode" class="form-control" readonly="#(true)" />
<span asp-validation-for="ItemCode" class="text-danger"></span>
</div>
}
else
{
<div class="form-group">
<label asp-for="ItemCode" class="control-label"></label>
<select asp-for="ItemCode" class="form-control" asp-items="ViewBag.Name">
<option value="">-- Select Product Item --</option>
</select>
<span asp-validation-for="ItemCode" class="text-danger" />
</div>
}
</div>
Below is my controller code for adding OrderItems to Order:
'''
HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddOrderItem([Bind("Items")] Order order)
{
PopulateDepartmentsDropDownListAsync();
order.Items.Add(new OrderItem());
return PartialView("OrderItems", order);
}
'''
How can I now add multiple palletItems to each OrderItem?
Add a relation to your palletItems and OrderItem, and you can get all the properties
by using palletItems:
public class PalletItems
{
[Key]
public int id { get; set; }
[StringLength(100)]
[Display(Name = "Pallet Number")]
public string PalletNumber { get; set; }
//....
public OrderItem OrderItem { get; set; } //add this, (In Orderitem model, add Order)
}
To use it:
#model PalletItems
#Html.EditorFor(model => model.PalletNumber, new { #style = "border:0.2rem" })
#Html.EditorFor(model => model.OrderItem.Order.CashierName, new { #style = "border:0.2rem" })
Banging my head against a brick wall here. I have a Datatable that is populated by GET call to an api from a dropdown box. Ideally i want the user to select an option in the dropdown and the table will reload with the data from the call.
The api is getting called and data is being returned with each selection but the table doesnt display the data or get refreshed like i would expect.
CheckIn.cshtml
#model IEnumerable<Vidly.Models.Customer>
#{
ViewBag.Title = "CheckIn";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>CheckIn</h2>
<div class="form-group">
#Html.DropDownList("Customers",
new SelectList(Model, "Id", "Name"), "Please select a customer",
new { #class = "form-control", #id = "customers"})
</div>
<table id="rentals" class="table table-bordered table-hover">
<thead>
<tr>
<th>Id</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section scripts
{
<script>
$(document).ready(function () {
var customerId;
var table = $("#rentals").DataTable({
ajax: {
type: 'GET',
url: '/api/RentalsApi/',
data: function (d) {
d.id = customerId ? customerId : -1;
},
dataSrc: ""
},
columns: [
{
data: "name"
}
]
});
$('#customers').on('change', function (e) {
console.log(this.value);
customerId = this.value;
table.ajax.reload();
});
});
</script>
}
API
// GET /api/RentalsApi/{1}
[HttpGet]
public IHttpActionResult GetRental(int id)
{
if (id == -1) return Json(new System.Web.Mvc.EmptyResult());
var customer = _context.Customers.SingleOrDefault(c => c.Id == id);
return Ok(customer);
}
Customer Model
using System;
using System.ComponentModel.DataAnnotations;
namespace Vidly.Models
{
public class Customer
{
public int Id { get; set; }
[Required(ErrorMessage = "Please enter customer's name.")]
[StringLength(255)]
public string Name { get; set; }
public bool IsSubscribedToNewsletter { get; set; }
public MembershipType MembershipType { get; set; }
[Display(Name = "Membership Type")]
public byte MembershipTypeId { get; set; }
[Display(Name = "Date of Birth")]
[Min18YearsIfAMember]
public DateTime? Birthdate { get; set; }
}
}
Just make your ajax api call as normal and then use this to redraw the table
table=$("#rentals").DataTable()
table.clear().rows.add(newData).draw(); //newData is the data you get from your ajax call
how to next page with ajax and jquery in mvc ?
I'm using the code below
#model DGM.Common.PageInput
#using System.Globalization
<link href="~/Content/themes/jquery-ui.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
<script>
function NextPage() {
//TODO
}
</script>
<div class="scroll-pane ui-widget ui-widget-header ui-corner-all">
<div class="scroll-content" style="display: inline-table">
#for (int i = 1; i < Model.CountPage + 1; i++)
{
string idParametr = Model.NameIdParametr;
short valueIdParametr = Model.ValueIdParametr;
var routeValueDictionary = new RouteValueDictionary
{
{idParametr, valueIdParametr},
{"countryNo", Model.CountryNo},
{"count", Model.CountRecordInPage},
{"page", i}
};
if (Model.IsSearch)
{
routeValueDictionary.Add("search", Model.TextSearch);
}
#Ajax.ActionLink(i.ToString(CultureInfo.InvariantCulture), Model.ActionName, Model.Controller,
routeValueDictionary,
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnSuccess",
UpdateTargetId = "grid-list",
InsertionMode = InsertionMode.Replace
}, new Dictionary<string, object>
{
{"class", "scroll-content-item ui-widget-header"},
{"onclick", "clickfunc(this)"}
})
}
</div>
<div class="scroll-bar-wrap ui-widget-content ui-corner-bottom">
<div class="scroll-bar"></div>
</div>
</div>
<div class="InfoPaging" style="margin: 0 auto; text-align: center;">
<a id="LastPage"href="javascript:void(0);" style="color: blue; padding: 0 10px">Last Page</a>
<a id="NextPage" onclick="NextPage()" href="javascript:void(0);" style="color: blue; padding: 0 10px">Next Page</a>
<a id="PreviousPage" href="javascript:void(0);" style="color: blue; padding: 0 10px">Previous Page</a>
<a id="FirsPpage" href="javascript:void(0);" style="color: blue; padding: 0 10px">First Page</a>
</div>
PageInput Class :
public class PageInput
{
public string ActionName { get; set; }
public string Controller { get; set; }
public int CountPage { get; set; }
public int AllRecord { get; set; }
public string NameIdParametr { get; set; }
public short ValueIdParametr { get; set; }
public decimal CountryNo { get; set; }
public int CountRecordInPage { get; set; }
public bool IsSearch { get; set; }
public string TextSearch { get; set; }
public int CurrentPage { get; set; }
}
I not have an idea for this work.I do not know what should I use.Whether from jQuery should I use?
I not have an idea for this work.I do not know what should I use.Whether from jQuery should I use?
update :
I've tried the following. But it always displays the second page
#{
idParametr = Model.NameIdParametr;
valueIdParametr = Model.ValueIdParametr;
routeValueDictionary = new RouteValueDictionary
{
{idParametr, valueIdParametr},
{"countryNo", Model.CountryNo},
{"count", Model.CountRecordInPage},
{"page", ++Model.CurrentPage}
};
if (Model.IsSearch)
{
routeValueDictionary.Add("search", Model.TextSearch);
}
}
#Ajax.ActionLink("Next Page", Model.ActionName, Model.Controller,
routeValueDictionary,
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnSuccess",
UpdateTargetId = "grid-list",
InsertionMode = InsertionMode.Replace
})
i found :
Update Partial View :
function NextPage() {
var dataToSend = #Html.Raw(Json.Encode(Model));
dataToSend.CurrentPage = #Model.CurrentPage + 1;
$.ajax({
url: '#Url.Action("GetPageNumbers", "Class")',
data: dataToSend,
success: function(dataa) {
$('#PagingList').html(dataa);
$('#PagingListUp').html($('#PagingList').html());
}
});
}
use Action Link For Next Page :
#{
idParametr = Model.NameIdParametr;
valueIdParametr = Model.ValueIdParametr;
routeValueDictionary = new RouteValueDictionary
{
{idParametr, valueIdParametr},
{"countryNo", Model.CountryNo},
{"count", Model.CountRecordInPage},
{"page", Model.CurrentPage+1}
};
if (Model.IsSearch)
{
routeValueDictionary.Add("search", Model.TextSearch);
}
}
#Ajax.ActionLink("Next Page", Model.ActionName, Model.Controller,
routeValueDictionary,
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnSuccess",
UpdateTargetId = "grid-list",
InsertionMode = InsertionMode.Replace
}, new Dictionary<string, object>
{
{"onclick", "NextPage()"}
})
Imagine below MVC parent model:
Model:
Namespace MyProject.SampleModel
{
public class ViewModelExample {
public FirstModel BoolValues { get; set; }
public SecondModel NamesValues { get; set; }
}
}
Namespace MyProject.SampleModel
{
public class FirstModel
{
public bool MyBoolean1 { get; set; }
public bool MyBoolean2 { get; set; }
}
public class SecondModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
View:
#model MyProject.SampleModel.ViewModelExample
#using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, htmlAttributes: new { id = "Myform" }))
{
(...)
#Html.CheckBoxFor(m => m.BoolValues.MyBoolean1)
(...)
<input id="submitButton" type="button" value="Add" onclick="InitiateSequence();" />
(...)
}
<script type="text/javascript" src="~/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
(...)
function InitiateSequence()
{
// Do some stuff
}
(...)
function ScriptSample() {
if(#(Model.BoolValues.MyBoolean1 ? "true" : "false")
{
// It's true, do some stuff
}
else
{
// It's false, do some stuff
}
}
</script>
Controller:
public ActionResult MyAction(ViewModelExample model)
{
model.FirstModel = new TestsModel(); // I do not instantiate SecondModel as in the view for this controller i do not use it
return View(model);
}
Page is loading correctly, but when I click on the button it says javascript function InitiateSequence is not defined.... what's happening?
That could be because most possibly the function appears where it is not supposed to be. Also don't use inline attributes to bind the handlers, use event binding instead of inline handler.
<input id="submitButton" type="button" value="Add" />
and
<script type="text/javascript">
(...) //whatever code
$(function(){
$('#submitButton').on('click', InitiateSequence);
});