In the view, the model is:
#model List<ParamsTaskLib.ParamRecord>
I want to create a form with an input field which will be the DeviceID to search for:
public class ParamRecord
{
[Required]
[RegularExpression(#"^[0-9a-fA-F]{8}$", ErrorMessage = "Invalid Device ID (hex)")]
public Int64 DeviceID { get; set; }
other fields in here...
I tried editing the view in the following way:
<form method="get" >
#Html.EditorFor(model => model.First().DeviceID)
#Html.ValidationMessageFor(model => model.First().DeviceID)
But it doesn't work obviously, it doesn't seem like it SHOULD work:)
I'm confused with how to work with a list as a model, combined with a search box...
The error I get is "Value can't be NULL" on this line:
#Html.EditorFor(model => model.First().DeviceID)
Extra clarification: the purpose of this page is to display a table which contains many lines (ParamRecord) of a specific DeviceID from the database.
The purpose of the form + input field is to supply the web server with the DeviceID of which I want to see data (a collection of ParamRecord)
This is the complete View page:
#model List<ParamsTaskLib.ParamRecord>
#{
ViewBag.Title = "SearchResults";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript" >
function UpdateFunc() {
$.get("/home/GetProgress", function(data) {
$("#UpdatePercentage").text(data);
if (data == "100")
location.reload();
else
setTimeout(UpdateFunc, 2000);
});
}
function Update() {
var id = $("#id").val();
$.post("#Url.Content("~/Home/UpdateID/")" + id, function (data) {
UpdateFunc();
});
$("#UpdateAni").attr("src", "#Url.Content("~/Content/Images/ajax-loader.gif")");
$("#UpdatePercentage").show();
}
</script>
<div>
<form method="get" >
#Html.TextBox("id")
#*#Html.EditorFor(model => model.First().DeviceID)*#
#Html.ValidationMessageFor(model => model.First().DeviceID)
<input type="submit" value="Search" />
<img id="UpdateAni" src="#Url.Content("~/Content/Images/ajax-loader_static.gif")" onclick="Update()"/>
<span id="UpdatePercentage" style="display:none" >0</span>
</form>
#if (Model != null )
{
<h4>ID 0x<span>#ViewBag.ID</span> , last update was at #ViewBag.LastUpdateTS</h4>
<h3>Total #ViewBag.NumOfParams parameters</h3>
<hr />
<table border="1" >
<thead>
<tr>
<th>Parameter Number</th>
<th>Device Inner ID</th>
<th>Device Type</th>
<th>Value (Int)</th>
<th>Value (Float)</th>
<th>Value (String)</th>
</tr>
</thead>
#for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>#Model[i].ParamIndex</td>
<td>#Model[i].DeviceInnerID</td>
<td>#Model[i].DeviceType</td>
<td>#Model[i].ParamValInt</td>
<td>#Model[i].ParamValFloat</td>
<td>#Model[i].ParamValSTR</td>
</tr>
}
</table>
}
else if (ViewBag.NoResults == 1)
{
<h3>No results for ID 0x<span>#ViewBag.ID</span></h3>
}
</div>
Related
I want to repeat a dropdownlist that is already bound using a Viewbag property and another textbox when a user click on Add Course.
I have used asp.net mvc and knockout.js based on a tutorial i saw, but the tutorial does not exactly handle using bound controls, please how can i achieve this using asp.net mvc and knockout.js.
Below is my code.
Thanks
<table id="jobsplits">
<thead>
<tr>
<th>#Html.DisplayNameFor(m => m.selectedCourse.FirstOrDefault().FK_CourseId)</th>
<th>#Html.DisplayNameFor(m => m.selectedCourse.FirstOrDefault().CourseUnit)</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: courses">
#for (int i = 0; i < Model.selectedCourse.Count; i++)
{
<tr>
<td>
#Html.DropDownListFor(model => model.selectedCourse[i].FK_CourseId, new SelectList(ViewBag.Course, "Value", "Text", Model.FK_CourseId), "Select Course", new { #class = "form-control", data_bind = "value: courses" })
</td>
<td>
#Html.TextBoxFor(model => model.selectedCourse[i].CourseUnit, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly", data_bind = "value: courseUnit" } })
</td>
<td>
<button type="button" data-bind="click: $root.removeCourse" class="btn delete">Delete</button>
</td>
</tr>
}
</tbody>
</table>
<div class="col-md-4">
<button data-bind="click: addCourse" type="button" class="btn">Add Course</button>
</div>
This is the script section
#section Scripts{
#Scripts.Render("~/bundles/knockout")
<script>
function CourseAdd(course, courseUnit) {
var self = this;
self.course = course;
self.courseUnit = courseUnit;
}
function CourseRegViewModel() {
var self = this;
self.addCourse = function () {
self.courses.push(new CourseAdd(self.course, self.courseUnit));
}
self.courses = ko.observableArray([
new CourseAdd(self.course, self.courseUnit)
]);
self.removeCourse = function (course) {
self.courses.remove(course)
}
}
ko.applyBindings(new CourseRegViewModel());
</script>
}
Edit:
i have been able to get this sample working from: http://learn.knockoutjs.com/#/?tutorial=collections
but it is only an hard-coded observableArray.
I want to be able to populate the select from the database. But it is not getting populated.
This is my sample code below:
<table id="jobsplits">
<thead>
<tr>
<th>Persenger Name</th>
<th>Meal</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: seats">
<tr>
<td>
<input data-bind="value: name" />
</td>
<td>
<select data-bind="options:coursesArray, optionsText:'Text', optionsValue:'Value', optionsCaption: 'Choose...'"></select>
</td>
<td>
<button type="button" data-bind="click: $root.removeSeat" class="btn delete">Delete</button>
</td>
</tr>
</tbody>
</table>
<div class="col-md-4">
<button data-bind="click: addSeat">Add Seat</button>
</div>
This is the adjusted script section:
<script>
function SeatReservation(name, initialMeal) {
var self = this;
self.name = name;
self.meal = ko.observable(initialMeal);
}
function ReservationsViewModel() {
var self = this;
//This is what i want to put in dropdown instead
self.thecourses.subscribe(function () {
getCourses();
});
// Editable data
self.seats = ko.observableArray([
new SeatReservation("Steve", self.thecourses),
new SeatReservation("Bert", self.thecourses)
]);
self.addSeat = function () {
self.seats.push(new SeatReservation("", self.availableMeals[0]));
}
self.removeSeat = function (seat) { self.seats.remove(seat) }
var getCourses = function () {
var collegeCode = $("#Colleges").val();
var departmentCode = $("#Departments").val();
var url = '#Url.Action("GetCourses", "Student")';
$.getJSON(url, { deptId: departmentCode, collegeId: collegeCode }, function (data) {
self.coursesArray(data)
});
}
}
ko.applyBindings(new ReservationsViewModel());
</script>
I've been struggling with this for a while now. I'm constructing this view:
But when I hit the 'Update' button after do some changes the web refreshes to show the original values.
About the view: I get this view using an IEnumerable and looping thru each item in the model inside a form. Then, inside the form, there is a table that contains only 1 row. I do this in order to wrap all the items of the record in one form. This is part of code:
#foreach (var item in Model)
{
<form asp-action="Test" asp-route-id="#item.Id">
<table class="table">
<tbody>
<tr>
<td>
<input type="hidden" asp-for="#item.Id" />
<div class="form-group">
<div class="col-md-10">
<input asp-for="#item.MchName" readonly class="form-control" />
<span asp-validation-for="#item.MchName" class="text-danger"></span>
</div>
</div>
</td>
//more fields
<td>
<input type="submit" value="Update" class="btn btn-default" />
</td>
</tr>
</tbody>
</table>
</form>}
I declare an asp-action and a asp-route-id:
<form asp-action="Test" asp-route-id="#item.Id">
Question: Is this good enough? Is there something missing?
This is the Get Method:
public async Task<IActionResult> Test()
{
PopulateMachineTypeDropDownListStore();
return View(await _context.Machines.AsNoTracking().ToListAsync());
}
Question: I'm not passing any argument to the controller, yet the view will list the items following the given structure using an IEnumerable. Should I pass anything to the Get Method or is it fine as it is?
This is the Post Method:
#model IEnumerable<Application.Models.Machine>
[HttpPost, ActionName("Test")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> TestPost(int? id)
{
if (id == null)
{
return NotFound();
}
var machinetoUpdate = await _context.Machines
.SingleOrDefaultAsync(s => s.Id == id);
if (await TryUpdateModelAsync(
machinetoUpdate,
"",
s => s.MchName, s => s.StoreID, s => s.PUnit, s => s.Status))
{
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists, " +
"see your system administrator.");
}
return RedirectToAction("Test");
}
PopulateMachineTypeDropDownListStore();
return View(await _context.Machines.AsNoTracking().ToListAsync());
}
Question: I don't know if because the entity I retrieve the id from (and that I use to update the model thru TryUpdateModelAsync()) is also being used to compare to the model that thru the view this might not been working properly.
Thanks in advance for any help.
Hi I have the following data table in which u can click move button , the issue is that it always use get link instead of post how to apply post with parameters
<div class="box-body">
#using (#Html.BeginForm("QueueDetails", "Home", FormMethod.Post))
{
<table id="example1">
<tbody>
#foreach (var errorMesseage in Model.ErrorMesseages)
{
<tr>
<td>#errorMesseage</td>
<td>
#Html.ActionLink(
"Move",
"QueueDetails",
new { errorMesseage = #errorMesseage, model = Model },
new { #class = "saveButton", onclick = "return false;" })
</td>
</tr>
}
</tbody>
</table>
}
</div>
$(document).ready(function () {
createChart();
$('.saveButton').click(function () {
if(confirm('Are you sure you wish to Move this messeage back?'))
{
$(this).closest('form')[0].submit();
}
});
});
it always redirect to the get with url like Home/QueueDetails?errorMesseage=Error%20messeage%201&model=xxxx
i have a MvcApplication for Store WebSite and i want when user go to Products and when click on Buy for each of product,go to a view that will reviews Buy List and make sure's user are accepted,then after user clicked on IAccept return to Index View with a Message
now my problem is this,i can't use passed product object in my View,error message is this:"#Model.name is null"
here is my Product,Buy ActionResult and Buy,Product View
public ActionResult Product()
{
var pmodel = db.posts.ToList();
product pro = new product()
qrcode = 2455174,
name = "hub",
color_id = 3,
category_id = 3,
price = 10,
maker_code = 1,
offer_id = 0
};
db.products.Add(pro);
db.SaveChanges();
if (pmodel != null)
{
return View(pmodel);
}
return View();
}
Product View:
#model IEnumerable<MvcApplication1.Models.post>
#{
ViewBag.Title = "Product";
Layout = "~/Views/Shared/_LayoutHome.cshtml";
}
<h3>Products</h3>
<html>
<head><title></title>
<script type="text/javascript">
function enlarge(el) {
if (el.width = 300)
{
el.width = 50;
el.height = 50;
}
el.width = 300;
el.height = 240;
}
</script>
</head>
<body>
<table>
<tr>
<td style="font-weight:bold">
Image:
</td>
<td style="font-weight:bold">
Name:
</td>
<td style="font-weight:bold">
Description:
</td>
</tr>
#foreach(var item in Model) {
<tr>
<td>
<img src="~/Resources/image_2.jpg") id="x"
width="50" height="50" onclick="enlarge(this)"
alt="Click To See Image Larger">
</td>
<td>
#Html.DisplayFor(modelItem => item.title)
</td>
<td>
#Html.DisplayFor(modelItem => item.text)
</td>
<td>
#using (Html.BeginForm()){
<p>
#Html.ActionLink("Buy Now!", "Buy")
</p>
}
</td>
</tr>
}
</table>
</body>
</html>
Buy ActionResult:
[HttpPost]
public ActionResult Buy(user users,product products,post p)
{
var prod = db.products.Single(pro => pro.qrcode == products.qrcode);
DateTime date = DateTime.Now;
factor fact = new factor() {description=p.text,factor_id=products.qrcode,count=1
,product_name=products.name,product_qrcode=products.qrcode,status=
"Buy with Balance fFunds",date=date.ToString()};
return View(prod);
}
[HttpGet]
public ActionResult Buy(product products)
{
return View(products);
}
And Here is Buy View:
#model MvcApplication1.Models.product
#{
ViewBag.Title = "Buy";
Layout = "~/Views/Shared/_LayoutHome.cshtml";
}
<h2>Review</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Are you sure to buy this stuff?</legend>
</fieldset>
<div class="display">
#Html.DisplayFor(model => model.name)
</div>
<div class="display">
#Html.DisplayFor(model => model.price)
</div>
<div class="display">
#Html.DisplayFor(model => model.qrcode)
</div>
<p>
<input type="submit" value="Accept" />
</p>
}
my problem summary is,when user go to products and see the products post's and try to buy something (by clicking on "Buy Now!" link)then will be Redirect to Buy View,then user must reviews and Accept stuff details then Redirect to Index with a Message from complete operation or something like that!!But it doesn't show stuff details.
I have taken over support of an MVC application, but unfortunately have pretty much zero experience or knowledge of MVC, so I apologise in advance if this is a stupid question.
We are placing every single result into a listed item in the HTML, then hiding all but one record, so you can filter through the different entries using First/Prev/Next/Last buttons, all via jQuery:
$("a#next").on("click", function () {
var nextli = $("li.first");
if ($(nextli).is(":last-child")) {
return false;
}
nextli.removeClass("first").addClass("record").next().addClass("first").removeClass("record");
});
$("a#previous").on("click", function () {
var nextli = $("li.first");
if ($(nextli).is(":first-child")) {
return false;
}
nextli.removeClass("first").addClass("record").prev().addClass("first").removeClass("record");
});
This is fine, and displays the records without any problem, however when you try to edit any record but the first, you get a "System.ArgumentNullException: Value cannot be null." error.
Here's the code in the controller for the edit function:
[HttpPost]
public ActionResult Edit(RecordsView rv)
{
if (ModelState.IsValid)
{
repository.EditRecord(rv.Records.FirstOrDefault().DogIncident);
}
return RedirectToAction("Index");
}
This is defined at the start of the cshtml file:
#using (Html.BeginForm("Edit", "Home", FormMethod.Post,new {#class="record-view"}))
And finally, here is how the HTML is generated on the view:
<li class="first" id="record-1805">
<form action="/Home/Edit" class="record-view" method="post">
<ul>
[form elements]
<li><input type="submit" style="margin: 18px 0;" value="Save"></li>
</ul>
</form>
</li>
<li class="record" id="record-1804">
<form action="/Home/Edit" class="record-view" method="post">
<ul>
[form elements]
<li><input type="submit" style="margin: 18px 0;" value="Save"></li>
</ul>
</form>
</li>
<li class="record" id="record-1803">
<form action="/Home/Edit" class="record-view" method="post">
<ul>
[form elements]
<li><input type="submit" style="margin: 18px 0;" value="Save"></li>
</ul>
</form>
</li>
Does anyone please know why I can only edit the first record that is displayed and not the others? Even if I go through the records using the next/back buttons and back to the first record to submit it, it updates fine, but updating any other record generates an error.
Referencing Darin's post: Pass a parameter to a controller using jquery ajax takes you halfway. He's using an input val in jQuery and passing it to the Controller Action.
Typically you'd provide one input link or #Html.ActionLink per record to be clicked for editing and MVC will bind to the controls parameter to your action (ID or what ever you want) just use the same name on the action link as the parameter and it will be mapped during the post.
data: { input: $('#caption').val() },
Change the signature of your controller action , or add another that takes an 'int' as shown below.
[HttpPost]
public ActionResult Edit(int ID = 0)
{
if (ModelState.IsValid)
{
repository.EditRecord(rv.Records.Where(r => r.ID == ID).DogIncident);
}
return RedirectToAction("Index");
}
Can you post the complete view so we can complete a solution ?
Was expecting the cshtml view. Here's an example:
#model IEnumerable<yourModelName>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.NID)
</th>
<th>
#Html.DisplayNameFor(model => model.CreatedOn)
</th>
<th>
#Html.DisplayNameFor(model => model.ExtensionAttribute15)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.yourElement1)
</td>
<td>
#Html.DisplayFor(modelItem => item.yourElement2)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
</td>
</tr>
}
</table>
#section Scripts{
<script type="text/javascript">
$("a#next").on("click", function () {
var nextli = $("li.first");
if ($(nextli).is(":last-child")) {
return false;
}
nextli.removeClass("first").addClass("record").next().addClass("first").removeClass("record");
});
$("a#previous").on("click", function () {
var nextli = $("li.first");
if ($(nextli).is(":first-child")) {
return false;
}
nextli.removeClass("first").addClass("record").prev().addClass("first").removeClass("record");
});
</script>
}