How to work with checkboxes in ASP.NET MVC? - javascript

I have a view inside which there are two checkboxes. On checked I need to save currently assigned value into database table.
Here is the model:
public class RoomHk
{
public int RoomHkId { get; set; }
public int RoomId { get; set; }
public DateTime? DeepCleaning { get; set; }
public DateTime? NewLinen { get; set; }
}
This is the child table of my Room Table. Following is my view, suppose user check on first checkbox then he clicks on save button, then I want to save current datetime in the NewLinen column of the RoomHk table to that respective RoomId. How can I do it with jQuery post method?
<div class="col-6">
#if (item.NewLinen == null)
{
<input type="checkbox" data-nlid="#item.RoomId" class="form-check-input newLinen" />
<label>New Linen</label>
<br />
}
#if (item.DeepCleaning == null)
{
<input type="checkbox" data-dcid="#item.RoomId" class="form-check-input deepClean" />
<label>Deep Cleaning</label>
}
</div>
<button type="button" class="btn btn-default insert" data-rid="#item.RoomId">Save</button>
$(function () {
$('.insert').click(function () {
$.post("#Url.Action("SetCleaningStatus", "HouseKeeping")", { id: $(this).data("id"), });
});
});

You could use Html.BeginForm and place the submit button inside the form. This is important, otherwise you'll need to employ additional scripts to get it working.
If you need to post the state of the two checkboxes (DeepCleaning and NewLinen) I'd suggest having them as Boolean instead of DateTime so you can have their states (checked/unchecked) mapped to the respective properties, because you seem to want to do that.
SetCleaningStatus.cshtml
#model RoomHk;
#Html.BeginForm("SetCleaningStatus", "HouseKeeping")
{
<!-- Will be posted to the controller, no additional Javascript necessary -->
#Html.HiddenFor(m => m.RoomId)
<div class="col-6">
#if (item.NewLinen == null)
{
<input type="checkbox" data-nlid="#item.RoomId" class="form-check-input newLinen" />
<label>New Linen</label>
<br />
}
#if (item.DeepCleaning == null)
{
<input type="checkbox" data-dcid="#item.RoomId" class="form-check-input deepClean" />
<label>Deep Cleaning</label>
}
</div>
<!-- IMPORTANT: the type needs to be `submit` instead of `button` -->
<input type="submit" class="btn btn-default insert" value="Save" />
}
HouseKeeping.cs
public class RoomHk
{
public int RoomHkId { get; set; }
public int RoomId { get; set; }
public DateTime? DeepCleaning { get; set; }
public DateTime? NewLinen { get; set; }
}
[HttpGet]
public ActionResult SetCleaningStatus()
{
var model = new RoomHk();
return View(model);
}
[HttpPost]
public ActionResult SetCleaningStatus(RoomHk arg)
{
bool response = new {
success = true
};
// Here is your RoomId
arg.RoomId;
arg.NewLinen = DateTime.Now;
// Save posted data to DB
// ...
// Return your response here
return Json(response);
}
POSTting the checked state of checkboxes
Use Html.CheckBoxFor and Html.LabelFor and let the compiler render those fields for you, with the right IDs and names properly set.
public class RoomHk
{
// Make them booleans
public bool DeepCleaning { get; set; }
public bool NewLinen { get; set; }
}
<div class="col-6">
<!--
<input type="checkbox" data-nlid="#item.RoomId" class="form-check-input newLinen" />
<label>New Linen</label>
<br />
-->
#Html.LabelFor(m => m.NewLinen, "New Linen")
#Html.CheckBoxFor(m => m.NewLinen, new { #class = "form-check-input" })
</div>

Related

Asp.net Core PartialView submits form unnecessarily

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>

editfor inside editorfor, for dynamic list in asp.net core

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" })

get result of javascript function and post it as additional form data

I have JS function that is basically
<script type="text/javascript">
function doSomething() {
var s = 'some data'
return s; }
</script>
and
#using (Html.BeginForm(new { data_to_send = x))
{
//some form controls that are sent to controller via model
}
Is it possible, and how, to assign value returned by doSomething function to x variable in form?
I don't need x in my model, because it won't go to database. It's just some additional info from user, how to manipulate data in model before saving to database.
edit: Controller action is
public actionresult MyController(string data_to_Send, model) {}
In the View:
#using (Html.BeginForm())
{
#Html.HiddenFor(model => model.X1)
#Html.HiddenFor(model => model.X2)
}
In the Model:
public class YourModel
{
public string X1 { get; set; }
public string X2 { get; set; }
}
In the Controller:
[HttpPost]
public ActionResult Index(YourModel model)
{
string x1 = model.X1;
string x2 = model.X2;
return View(model);
}
The form has to be posted in order to do what you are looking for.
You can post the model along with PostedDateValue
#using (Html.BeginForm("ActionMethod", "Controller", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-field required">
<label for="Posted Data">Posted Data</label>
<input id="txtPostedData" name="PostedDateValue" >
<input type="submit" class="gradient" value="SUBMIT" />
</div>
}
)
Controller
public ActionResult ActionMethod(string PostedDateValue)
{
}

Setup for ASP.NET MVC and Javascript / jQuery?

My JavaScript will not run. I've been struggling with this for a while (2 days) Here's my current setup:
Created a new MVC 4 project. I intend to try out some AJAX, so named it AjaxTest.
Added a model (Vehicle.cs) consisting of three classes OdometerInfo, VehicleMinInfo, and Vehicle. Here they are:
public class OdometerInfo
{
public virtual string VIN { get; set; }
public virtual int Odometer { get; set; }
}
public class VehicleMinInfo : OdometerInfo
{
public virtual Nullable<int> VehicleYear { get; set; }
public virtual string Make { get; set; }
public virtual string Model { get; set; }
}
public class Vehicle : VehicleMinInfo
{
// default constructor
public Vehicle()
{
VIN = "MyFakeVin";
Odometer = 0;
VehicleYear = 2012;
Make = "Porsche";
Model = "911";
}
public override string VIN { get; set; }
public override int Odometer { get; set; }
public override Nullable<int> VehicleYear { get; set; }
public override string Make { get; set; }
public override string Model { get; set; }
// other fields
}
Then I replaced the contents of the template Index.cshtml with:
#model AjaxTest.Models.VehicleMinInfo
#{
ViewBag.Title = "Index";
}
<h2>Enter your odometer reading</h2>
#using (Html.BeginForm("Odometer", "Home", FormMethod.Post))
{
<h4>For the following vehicle.</h4>
#Html.DisplayFor(model => model.VIN) <br />
#Html.DisplayFor(model => model.VehicleYear) <br />
#Html.DisplayFor(model => model.Make) <br />
#Html.DisplayFor(model => model.Model) <br />
<h1>Enter Odometer</h1>
#Html.DisplayNameFor(model => model.Odometer)
#Html.EditorFor(model => model.Odometer)
#Html.HiddenFor(model => model.VIN);
<input type="submit" value="Odometer reading is correct" id="OdometerForm" />
}
Then I made a strongly typed view (Odometer.cshtml):
#model AjaxTest.Models.OdometerInfo
#{
ViewBag.Title = "Odometer";
}
<h2>Odometer</h2>
Your odometer has been entered. It is
#Html.DisplayFor(model => model.Odometer)
. (
#Html.DisplayFor(model => model.VIN)
)
And added to the controller:
public ActionResult Index()
{
VehicleMinInfo OdomObj = new Vehicle();
return View(OdomObj);
}
[HttpPost]
public ActionResult Odometer(OdometerInfo oi)
{
return View(oi);
}
All of that works. I can fill in an odometer reading and both the odometer and the VIN are passed back to the controller and displayed on the Odometer page. Now, it's time to start adding some JavaScript. So I created OdometerList.js with the eventual goal of passing back a list of odometer readings instead of just one, and in it I placed:
$("#OdometerForm").click(function () {
alert("Hello world!");
});
window.onload = function () {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}
$(document).ready(function () {
alert("!!!");
});
Then I added in _Layout.cshtml
#Scripts.Render("~/Scripts/jquery-1.3.2.min.js")
#Scripts.Render("~/Scripts/OdometerList.js")
And I double checked Web.config to be sure compilation debug was true:
<system.web>
<compilation debug="true" targetFramework="4.5" />
...
None of my alerts are triggered, not one. Is my setup wrong? I moved my JavaScript from OdometerList.js to the bottom of Odometer.cshtml and put it all between script tags, but there was no change. I am new to JavaScript, so have I made a mistake there?
This is really stumping me. Any help you can give will be much appreciated!
The version of jQuery had been updated. Once I put the correct version number in, I was able to use #Scripts.Render("~/Scripts/jquery-1.8.2.min.js") and everything works!

javascript function not defined error on click on a button

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);
});

Categories

Resources