I am getting an error message that says:
Exception Details: System.InvalidOperationException: The view 'Index' or its
master was not found or no view engine supports the searched locations. The
following locations were searched:
~/Views/Request/Index.aspx
~/Views/Request/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Request/1819.master
~/Views/Shared/1819.master
~/Views/Request/1819.cshtml
~/Views/Request/1819.vbhtml
~/Views/Shared/1819.cshtml
~/Views/Shared/1819.vbhtml
I've seen several different post about this but none of those answers have solved my problem. I tried clicking through the views in visual studio and it sends me to the appropriate methods. I tried adding a home controller with a home view and an Index but that does not help as well. I tried modifying my route config and that didn't work either.
Here is my return statement that is giving me issues:
return View("Index", requestVM.AidYear);
I am calling this method:
public ActionResult Index(string aidYear)
I tried this:
return View("Index", (object)requestVM.AidYear);
and I tried this:
return View("Index", model:requestVM.AidYear);
With the last 2 I get:
System.InvalidOperationException: The model item passed into the dictionary is of type 'System.String', but this dictionary requires a model item of type 'ScholarshipDisbursement.ViewModels.Request.RequestViewModel'.
This occurs on my local machine and on our production server. The team I'm on are sure that this was working when we published it because this is a pretty big issue to not have noticed so we aren't sure why it is no longer working. No changes have been made to production since we published this application so we know no one has done something to screw it up.
Just in case this helps here is my route config:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Request", action = "Index", id = UrlParameter.Optional }
);
}
Edit:
In my view I have a folder Request and inside that folder is an Index.cshtml. On that view I have a form that submits to the method SubmitScholarshipRequest. That method is on the Request Controller.
In that method I run various checks and if there is an error I add it to the ModelState. If the ModelState is invalid I then:
return View("Index", requestVM.AidYear);
Otherwise I:
return RedirectToAction("Index", "Request", new { #aidYear = requestVM.AidYear });
Here is my view:
#using ScholarshipDisbursement.Helpers
#using ScholarshipDisbursement.ViewModels.Request
#model RequestViewModel
#{
ViewBag.Title = "Scholarship Request";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="requestIndexRoundedShadow">
<div class="pageTitleHeader">
<span><img src="~/Content/img/gradCap.ico" class="headerImg" /></span>
<span class="headerTitle"><b>Scholarship Disbursement Request</b></span>
<hr style="border-top: 1px solid black">
#using (Html.BeginForm("SubmitScholarshipRequest", "Request",
FormMethod.Post, new { id = "SubmitTutorRequestFrm" }))
{
#Html.AntiForgeryToken()
<span id="aidYearLbl" Style="font-size: 14px;font-weight: bold">Academic
Year: </span>
#Html.DropDownListFor(m => m.AidYear, new SelectList(Model.AidYears,
"Code", "Name"), new { id = "aidYear", onchange = "onChangeYear()", Style =
"font-size: 14px" })
if (Model.Scholarships.Any())
{
<br />
<br />
<table style="width: 100%;">
<tr>
<th class="headerBox tableHeader" colspan="3">Scholarships
for #Model.User.DeptName</th>
</tr>
<tr>
<th class="headerBox columnHeader" style="width:
500px;">Scholarship Name</th>
<th class="headerBox columnHeader" style="width:
100px;">Amount</th>
<th class="headerBox columnHeader" style="width:
100px;">Requested</th>
</tr>
#{ int i = 1; }
#foreach (var s in Model.Scholarships)
{
var rowColor = i % 2 == 0 ? "E8E8E8" : "ffffff";
<tr style="background-color: ##rowColor;">
<td class="rowValue">#Html.ActionLink(s.Name,
"ScholarshipRequest", "Request", new { aidYear = s.AidYear, fundCode = s.Id,
}, new { target = "_blank" })</td>
<td class="rowValue">#s.AmountTotal</td>
<td class="rowValue">#s.AmountRequested</td>
</tr>
i++;
}
</table>
<br />
<br />
if (Model.AvailScholarships.Any())
{
<table style="width: 100%">
<tr>
<th class="headerBox tableHeader" colspan="6">Request
Scholarship</th>
</tr>
<tr>
<th class="headerBox columnHeader">Scholarship</th>
<th class="headerBox columnHeader">Banner Id</th>
<th class="headerBox columnHeader">Student Name</th>
<th class="headerBox columnHeader">Amount</th>
<th class="headerBox columnHeader">Term</th>
<th class="headerBox columnHeader">Comments</th>
</tr>
<tr>
<td class="rowValue" style="width: 200px">#Html.DropDownListFor(m => m.ScholarshipId, new SelectList(Model.AvailScholarships, "Id", "Name"), "", new { id = "scholars" })</td>
<td class="rowValue" style="width: 125px">#Html.TextBoxFor(m => m.StudentId, new { autocomplete = "off", Style = "width:100%", id = "bannerId", maxlength = "9" })</td>
<td class="rowValue" style="width: 225px"><span id="studentName"></span></td>
<td class="rowValue" style="width: 50px">#Html.TextBoxFor(m => m.Amount, new { autocomplete = "off", Style = "width:100%", id = "amount", Value = "", data_val_number = " " })</td>
<td class="rowValue" style="width: 70px">#Html.DropDownListFor(m => m.Term, new SelectList(Model.Terms, "Code", "Name"), "", new { Style = "width:70px", id = "term" })</td>
<td class="rowValue" style="width: auto">#Html.TextBoxFor(m => m.Comments, new { autocomplete = "off", Style = "width:100%", id = "comments" })</td>
</tr>
<tr>
<td>#Html.ValidationMessageFor(m => m.ScholarshipId)</td>
<td>#Html.ValidationMessageFor(m => m.StudentId)</td>
<td></td>
<td>#Html.ValidationMessageFor(m => m.Amount)</td>
<td>#Html.ValidationMessageFor(m => m.Term)</td>
<td>#Html.ValidationMessageFor(m => m.Comments)</td>
</tr>
</table>
<br />
<input type="submit" id="SubmitNomineeBtn" name="SubmitNomineeBtn" class="submitButton" value="Submit" />
<span id="warning"></span>
<br />
<br />
<div class="field-validation-error">
#Html.ErrorFor(ViewData, "ExceedsAmountError")
</div>
<div class="field-validation-error">
#Html.ErrorFor(ViewData, "DuplicateEntryError")
</div>
<div class="field-validation-error">
#Html.ErrorFor(ViewData, "NullStudent")
</div>
<div class="field-validation-error">
#Html.ErrorFor(ViewData, "NegativeAmount")
</div>
}
else
{
<div style="padding-right: 100px">
<img src="~/Content/img/alert.png" /> There are currently no funds available for the #Model.User.DeptName department.
</div>
}
}
else
{
<br />
<br />
<div style="padding-right: 100px">
<img src="~/Content/img/alert.png" /> There are currently no scholarships available for the #Model.User.DeptName department.
</div>
}
}
</div>
<script>
$('#help').click(function() {
var win = $('#window').data("kendoWindow");
win.open();
win.center();
win.top();
});
$(document).ready(function () {
if ($('#bannerId').val()) {
checkBannerId();
}
});
function checkBannerId() {
var student = $('#bannerId').val();
$.ajax({
type: "POST",
url: '#Url.Action("GetStudentName","Request")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ bannerId: student }), // parameter aNumber
dataType: "json",
success: function (msg) {
if (msg.Result === "Null Student") {
$('#studentName').html("Error finding student name");
$('#studentName').css("color", "red");
$('#bannerId').css("border-color", "red");
$('#bannerId').css("color", "red");
$('#warning').html("Invalid Banner Id.");
$('#warning').css('color', 'red');
return;
} else {
$('#bannerId').css("border-color", "unset");
$('#bannerId').css("color", "black");
$('#studentName').html(msg.Result);
$('#studentName').css('color', 'black');
$('#warning').html("");
$('#warning').css('color', 'unset');
}
},
error: function () {
}
});
}
function onChangeYear() {
window.location = '#Url.Action("Index", "Request")?aidYear=' + $("#aidYear").val();
}
$('#amount').blur(function () {
if (isNaN($('#amount').val()) || $('#amount').val() < 0) {
$('#warning').html("Invalid amount ($, commas, and negative numbers not allowed).");
$('#warning').css('color', 'red');
$('#amount').css("border-color", "red");
$('#amount').css('color', "red");
} else {
$('#amount').css("border-color", "unset");
$('#amount').css("color", "unset");
$('#warning').html("");
$('#warning').css('color', 'unset');
}
});
$('#bannerId').blur(function () {
checkBannerId();
});
</script>
Here is the method the form calls:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SubmitScholarshipRequest(RequestViewModel requestVM)
{
var scholarshipMgr = new ScholarshipStore();
var scholarship = scholarshipMgr.GetScholarship(requestVM.ScholarshipId, requestVM.AidYear);
double amountTotal = scholarship.AmountTotal;
double amountRequested = scholarship.AmountRequested;
double addTotal = amountRequested + requestVM.Amount;
string username = User.Identity.Name;
var user = new UserStore().GetUser(username);
var student = new StudentStore().GetStudent(requestVM.StudentId);
if (student == null)
{
ModelState.AddModelError("NullStudent","Unable to find Student");
}
var scholarshipRequestMgr = new ScholarshipRequestStore();
var scholarshipRequest = scholarshipRequestMgr.GetScholarshipRequest(requestVM.StudentId, requestVM.ScholarshipId, requestVM.AidYear);
if (scholarshipRequest != null)
{
ModelState.AddModelError("DuplicateEntryError", "Scholarship already requested for this student!");
}
if (addTotal > amountTotal)
{
ModelState.AddModelError("ExceedsAmountError", "Amount entered exceeds the total available!");
}
if (addTotal < 0)
{
ModelState.AddModelError("NegativeAmount", "Must be a positive number");
}
if (!ModelState.IsValid)
{
var aidYears = new AidYearStore().GetAidYears();
var scholarships = new ScholarshipStore().GetScholarships(user.DeptCode, requestVM.AidYear);
var availableScholarships = scholarships.Where(x => x.AmountTotal > x.AmountRequested);
var terms = new TermStore().GetAllTerms();
requestVM.AidYears = aidYears;
requestVM.User = user;
requestVM.Scholarships = scholarships;
requestVM.AvailScholarships = availableScholarships;
requestVM.Terms = terms;
return View("Index", requestVM.AidYear);
}
var scholarShipRequest = new ScholarshipRequest
{
AidYear = requestVM.AidYear,
ScholarshipId = requestVM.ScholarshipId,
StudentId = requestVM.StudentId,
Amount = requestVM.Amount,
TermCode = requestVM.Term,
Comments = requestVM.Comments,
DeptId = user.DeptCode,
DateCreated = DateTime.Now,
CreatedBy = username,
PIDM = new StudentStore().GetStudent(requestVM.StudentId).PIDM
};
new ScholarshipRequestStore().CreateScholarshipRequest(scholarShipRequest);
return RedirectToAction("Index", "Request", new { #aidYear = requestVM.AidYear });
}
Here is the Index View Method from the RequestController:
public ActionResult Index(string aidYear)
{
aidYear = string.IsNullOrEmpty(aidYear) ? new FinAidYear().GetCurrentYear() : aidYear;
string username = User.Identity.Name;
if (!Authorization.CheckUsernameDept(username))
return RedirectToAction("NotAuthorized", "Account");
var user = new UserStore().GetUser(username);
var aidYears = new AidYearStore().GetAidYears();
var scholarships = new ScholarshipStore().GetScholarships(user.DeptCode, aidYear);
var availableScholarships = scholarships.Where(x => x.AmountTotal > x.AmountRequested);
var terms = new TermStore().GetAllTerms();
var requestVM = new RequestViewModel
{
AidYear = aidYear,
AidYears = aidYears,
User = user,
Scholarships = scholarships,
AvailScholarships = availableScholarships,
Terms = terms
};
return View(requestVM);
}
Your view expects a RequestViewModel, not a string. So giving it just the aid year will not work. That's what the "Index" action method expects, but here we're just loading the view directly, not executing the action method (after all, we're already executing a different action method). So you need to pass the whole viewmodel object in the return statement.
Additionally, because it's not an action method called "Index", you'll need to specify the name of the view you want to return.
I would expect that
return View("Index", requestVM);
would solve your problem.
It seems your view has the header :
#model ScholarshipDisbursement.ViewModels.Request.RequestViewModel
So, you should use that :
return View(requestVM);
For the application is expected all the viewModel.
Otherwise, we will need your structure for a better help.
I think the clue is in the error message. It's looking for a view named 1819.cshtml.
This is telling it to look for a view with the value of requestVM.AidYear to use for the master or template page.
return View("Index", requestVM.AidYear);
If you wanted to pass a model to the view use this instead. Instead of a string (which I assume requestVM.AidYear is) I'm passing something that's not a string. So it'll use requestVM as the model.
return View("Index", requestVM);
Alternatively, this may be what you want. to use
return RedirectToAction("Index", "Request", new { #aidYear = requestVM.AidYear });
Related
I'm using ASP.NET MVC and have a table with 9 columns which shows results from the database where the user can filter values based on columns. The table structure looks like this:
<table class="tableMain" id="x">
<thead>
<tr class="trMain">
<th class="thMain">
#Html.DisplayNameFor(model => model.ID)
</th>
<th class="thMain">
#Html.DisplayNameFor(model => model.YEAR)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr class="trMain">
<td class="tdMain">
#Html.DisplayFor(modelItem => item.ID)
</td>
<td class="tdMain">
#Html.DisplayFor(modelItem => item.YEAR)
</td>
<td class="tdMain">
<input type="checkbox" class="chkCheckBoxId" name="airlineId" value="#item.ID" />
</td>
<td class="tdMain">
#Html.ActionLink("EditValue", "Edit", new { id = item.ID })
</td>
</tr>
}
</tbody>
</table>
Now I need a button, so that the dynamically generated table opens in a new window and the print dialog opens automatically. I had this piece of code:
<div class="line-btn">
<input type="submit" value="print" onclick="printTable()" class="btn fl btn-print">
</div>
<script language="javascript">
function printTable()
{
var printContent = document.getElementById("x");
var windowUrl = 'about:blank';
var num;
var uniqueName = new Date();
var windowName = 'Print' + uniqueName.getTime();var printWindow = window.open(num, windowName, 'left=50000,top=50000,width=0,height=0');
printWindow.document.write(printContent.innerHTML);
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
}
</script>
The problem here is that the table is completely unsorted when printed so the rows/columns are shifted.
I found this example:
https://datatables.net/extensions/buttons/examples/print/simple.html
This is exactly what I need (open the table in a new window and open print dialog). But unfortunately this sample has a lot of code in the javascript files that I don't need. There is a search field included and a pagination.
Can someone help me please? Thank you very much!
Ok I found a good solution.
This is the code I used:
<script src="#Url.Content("~/Scripts/jquery-3.5.1.js")" type="text/javascript"></script>
<script>
var myApp;
myApp = (function (app) {
$('#x').click(function () {
myApp.print();
});
app.print = function () {
$.ajax({
url: 'Home/Print',
success: function (data) {
if (myApp.arePopupsBlocked()) {
alert('please allow popups.');
}
var printWindow = window.open();
if (printWindow) {
$(printWindow.document.body).html(data);
} else {
alert('please allow popups.');
}
},
error: function () {
alert('Error');
}
});
};
app.arePopupsBlocked = function () {
var aWindow = window.open(null, "", "width=1,height=1");
try {
aWindow.close();
return false;
} catch (e) {
return true;
}
};
return app;
})(window.myApp || {})
</script>
and right before the table-tag the link to click:
<style>
/* suppress link for printing */
##media only print {
a {
display: none;
}
}
</style>
[print table]
There opens no new window but the table is well formated for printing.
Hello guys i am working on a projekt where i can add articles to a cart. My cart is a partialview.When i add a Article to my cart the old data isnt stored and only one (the new article) article is added to my cart.
This is the code for the Post in my codebehind Im adding a Postition with RandomNumbers for testing
[BindProperty]
public List<Position> ArticlePositions { get; set; } = new List<Position>();
public PartialViewResult OnPostAddPosition(List<Position> articlePositions)
{
Random myObject = new Random();
Random myObject1 = new Random();
articlePositions.Add(new Position
{
ArticleAmount = myObject1.Next(10, 100),
ArticleId = myObject.Next(10, 100)
});
var partialViewResult = new PartialViewResult()
{
ViewName = "_ArticlePositonsPartial",
ViewData = new ViewDataDictionary<List<Position>>(ViewData, articlePositions),
};
return partialViewResult;
}
This is my Partialview with the Model:
#model List<Rechnungen.Models.Position>
<div class="tableFixHead">
<table class="table table-striped text-center table-sm ">
<thead class="table-dark ">
<tr>
<th style="width:72.5px" class="">Anzahl</th>
<th style="width:72.5px" class="">ID</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr id="">
<td style="width:72.5px" class="pt-2 ">
<span class="TBarticleAmount">#item.ArticleAmount</span>
</td>
<td style="width:72.5px" class="pt-2 ">
<span class="TBarticleType">#item.ArticleId</span>
</td>
</tr>
}
</tbody>
</table>
</div>
Where i render the Partial:
<div id="MyPartialView">
#{
await Html.RenderPartialAsync("_ArticlePositonsPartial", Model.ArticlePositions, ViewData);
}
</div>
How i add A Position to cart:
#Html.AntiForgeryToken()
<button class="btn btn-outline-secondary" onclick="GetPartialView()"><i class="fa-solid fa-plus"></i>Hinzufügen</button>
And this is my Javascript for it:
function GetPartialView() {
$.ajax({
type: "POST",
url: '?handler=AddPosition',
dataType: "html",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function(data) {
$("#MyPartialView").html(data);
},
error: function(result) {
alert("fail");
}
});
}
My code is working so far, when i add something to my cart my site is looking like this=>
When i click a second time on the add button my site looks like this=>
So my problem is that the Data in ArticlePositions isnt stored. When i Debugg my Code the ArticlePositions are NULL when the Post Method is called.
HTTP is stateless, so any state created in your OnPostAddPosition method is destroyed at the end of the request. You have to implement strategies to persist state across requests. There are a number of options available in Razor Pages. You should research them to identify the most suitable one for your application:
https://www.learnrazorpages.com/razor-pages/state-management
I am new to MVC and jQuery.
I am developing an Airline Reservation project in which I have 1 issue:-
If the Onward Flight & the Return Flight are on the same day, there should be a gap of at least 2 hours between the Onward Arrival Time & Return Departure Time. I am calling the same Select Action & passing in the Arrival Time as a parameter using :-
$.ajax({type: "GET", url: "/AirlineReservation/Select", data: {arrival:
$("#arrivalTime").val()}, success: function(data)
{$("#returnPanel").show();}});
This code above is in the click event of the Onward Radio button.
The relevant Select Action Method Code snippet is as follows:-
List<String> returnTimes = new List<String>();
IQueryable<String> returnTimesQuery = db.Flights.Where(f => f.SectorID == returnSectorID).OrderBy(f => f.DepartureTime).Select(f => f.DepartureTime);
foreach (String s in returnTimesQuery)
{
if (avm.ReturnDate2 == DateTime.Today.ToLongDateString())
{
Int32 departHour = Convert.ToInt32(s.Substring(0, 2));
Int32 departMinute = Convert.ToInt32(s.Substring(3, 2));
Int32 bookingHour = DateTime.Now.TimeOfDay.Hours;
Int32 bookingMinute = DateTime.Now.TimeOfDay.Minutes;
TimeSpan departTime = new TimeSpan(departHour, departMinute, 0);
TimeSpan bookingTime = new TimeSpan(bookingHour, bookingMinute, 0);
TimeSpan difference = departTime - bookingTime;
if (difference.Hours >= 2)
returnTimes.Add(s);
}
else
returnTimes.Add(s);
if (!String.IsNullOrEmpty(arrival))
{
if (avm.ReturnDate.Date == avm.DepartureDate.Date)
{
avm.ArrivalTime = arrival;
Int16 sameDayDepartHour = Convert.ToInt16(s.Substring(0, 2));
Int16 sameDayDepartMinute = Convert.ToInt16(s.Substring(3, 2));
Int16 arrivalHour = Convert.ToInt16(arrival.Substring(0, 2));
Int16 arrivalMinute = Convert.ToInt16(arrival.Substring(3, 2));
TimeSpan sameDayDepartTime = new TimeSpan(sameDayDepartHour, sameDayDepartMinute, 0);
TimeSpan arrivalTime = new TimeSpan(arrivalHour, arrivalMinute, 0);
TimeSpan sameDayDifference = sameDayDepartTime - arrivalTime;
if (sameDayDifference.Hours < 2)
returnTimes.Remove(s);
}
}
}
.......................more code
Finally I call :-
return View(avm);
where 'avm' is the View Model instance holding all the required information.
The "returnPanel"-section of the Select-View is as follows:-
<div id="returnPanel" class="panel panel-default panel-primary">
#if (Model.ReturnQueryCount)
{
var returnQueryList = Model.ReturnQuery.ToList();
<div class="panel-heading ">
<b>Returning Flight -
#ViewBag.ReturnSplit[0].ToString() to #ViewBag.ReturnSplit[1].ToString()
- #Model.ReturnDate2</b>
</div>
<div class="panel-body">
<table class="table table-bordered table-condensed"
id="returnTable">
<tr>
<th style="text-align: center;">Flight</th>
<th style="text-align: center;">Departs</th>
<th style="text-align: center;">Arrives</th>
<th style="text-align: center;">Economy</th>
<th style="text-align: center;">Business</th>
<th style="text-align: center;">First
Class</th>
</tr>
#for (Int16 i = 0; i < Model.ReturnQuery.Count();
i++)
{
<tr style="text-align: center;">
<td style="vertical-align:
middle;">#returnQueryList[i].FlightNumber</td>
<td style="vertical-align:
middle;">#returnQueryList[i].DepartureTime</td>
<td style="vertical-align: middle;">#returnQueryList[i].ArrivalTime</td>
................more markup and razor code
I am adding a row to the table for each Flight in the ReturnQuery property of the Model.
The Debugging shows the correct Flights are in the ReturnQuery property, but while rendering All the Return Flights on the same day get rendered in the table after selecting an Onward Flight instead of just the pertinent ones which are present in the ReturnQuery property. Why is this happening ?
I have solved the issue as follows:-
In my Select View, I have used the following code:-
#if (Model.Return)
{
using (Ajax.BeginForm("Return", null, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "returnDiv" }, new { id = "submitForm" }))
{
<input type="hidden" name="ArrivalTime" id="arrivalTime" />
#Html.Partial("_OnwardView")
}
<div id="returnDiv"></div>
}
else
{
#Html.Partial("_OnwardView")
}
Then in the onward radio button click event handler, I have called the submit method to force the postback to make it immediately responsive:-
$("#submitForm").submit();
Finally, in the Return-Action, I have used :-
return PartialView("_ReturnView", avm);
where "avm" is the ViewModel instance containing the updated information.
My function makes a search by ID and by name, and I'm doing it in MVC. The problem is that it enters the conditional (if) and the AJAX is run correctly, but then it also goes to the else and runs it too. Apparently my data in the dialog is blank because it send the alert window. It sometimes opens the dialog correctly, but when I change the module and come back the if and else are run again and the blank dialog appears.
What can be happening? When I make the first click, it blocks, I click again and then the data appears...
function buscaProducto(url, cod, name) {
if (cod.length != 0 || name.length != 0) {
var producto = name;
var identidad = cod;
$.ajax({
url: url,
type: "POST",
dataType: "html",
error: AjaxFailure,
beforeSend: AjaxBegin,
data: { productoNombre: producto, identidad: identidad },
success: function (data) {
$("#dialog").dialog({
bigframe: true,
modal: true,
autoOpen: true,
width: 900,
heigth: 700,
resizable: false,
});
$("#progressbar").hide();
$("#dialog").html(data);
console.log("Entregó los datos al #dialog");
}
});
}
else {
alert("<p>Debe ingresar una opcion de busqueda</p>", $(window).height() / 3)
this.abort();
}
}
I think the cache might be stuck
the controller
[HttpPost]
public ActionResult BusquedaProducto(string productoNombre, string identidad)
{
if (productoNombre.Equals(""))
{
if (identidad.Equals(""))
{
return HttpNotFound();
}
else
{
var code = (from p in db.GN_Portafolio
where p.CodigoPortafolio.StartsWith(identidad) && p.SenSerial == true
select p).ToList();
if (code.Equals("0"))
{
return HttpNotFound();
}
else
{
return View(code);
}
}
}
else
{
var producto = (from p in db.GN_Portafolio
where p.NombrePortafolio.StartsWith(productoNombre)
select p).ToList().Take(100);
if (producto.Equals("0"))
{
return HttpNotFound();
}
else
{
return View(producto);
}
}
}
the view
#model IEnumerable<SifActivoFijo.Models.GN_Portafolio>
<form class="items">
<label>items por Pagina: </label>
<select>
<option>5</option>
<option>10</option>
<option>15</option>
</select>
</form>
<input name="button" type="button" onclick="$('#dialog').dialog('close');" value="Cerrar" />
<table class="tablas">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.CodigoPortafolio)
</th>
<th>
#Html.DisplayNameFor(model => model.NombrePortafolio)
</th>
<th></th>
</tr>
</thead>
<tbody id="pagina">
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CodigoPortafolio)
</td>
<td>
#Html.DisplayFor(modelItem => item.NombrePortafolio)
</td>
<td>
<input class="seleccion" type="button" value="Seleccionar" />
</td>
</tr>
}
</tbody>
</table>
<div class="holder"></div>
<script type="text/javascript">
$(document).ready(function () {
$('input.seleccion').click(function () {
var codigo = $(this).parent().prev().prev();
var nombre = $(this).parent().prev();
$('#activoFijo_GN_Portafolio_CodigoPortafolio').val($.trim(codigo.text()));
$('#GN_Portafolio_CodigoPortafolio').val($.trim(codigo.text()));
$('#nombrePortafolio').val($.trim(nombre.text()));
$("#activoFijo_DescripcionActivoFijo").val($.trim(nombre.text()));
document.getElementById("dialog").innerHTML = '<div id="progressbar" class="progressbar" style="display: none;"></div>';
$("#dialog").dialog('close');
});
});
You are using return type as ActionResult in server side method. So this return your entire view, then page will get reload. So this has happening. So please change your methods return type to any other like string, Jsonresult, etc.,
I got this error when I am trying to remove the item from the Cart table.
HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Panier/RemoveFromCart/1. This URL seems to be fine with me. It should branch to the PanierController at RemoveCart. I don't understand why it is not branching.
Thanks
Index.cshtml
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Shopping Cart";
}
<script src="/Scripts/jquery-1.4.4.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Document.ready -> link up remove event handler
$(".RemoveLink").click(function () {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '') {
// Perform the ajax post
$.post("/ShoppingCart/RemoveFromCart", {"id": recordToDelete },
function (data) {
// Successful requests get here
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
});
}
});
});
</script>
<h3>
<em>Details</em> du panier:
</h3>
<p class="button">
#Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
</p>
<div id="update-message">
</div>
<table>
<tr>
<th>
Produit
</th>
<th>
Prix (unitaire)
</th>
<th>
Quantite
</th>
<th></th>
</tr>
#foreach (var item in Model.CartItems)
{
<tr id="row-#item.ProduitId">
<td>
#Html.ActionLink(item.Produit.Description,"Details", "Store", new { id =
item.ProduitId }, null)
</td>
<td>
#item.Produit.Prix
</td>
<td id="item-count-#item.ProduitId">
#item.Quantite
</td>
<td>
#Html.ActionLink("Enlever du panier", "RemoveFromCart", "Panier", new { id =
item.ProduitId }, null)
</td>
</tr>
}
<tr>
<td>
Total
</td>
<td></td>
<td></td>
<td id="cart-total">
#Model.CartTotal
</td>
</tr>
</table>
PanierController.cs
namespace Tp1WebStore3.Controllers
{
public class PanierController : Controller
{
Tp1WebStoreDBEntities dbProduit = new Tp1WebStoreDBEntities();
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the product to display confirmation
string produitDescription = dbProduit.Paniers
.Single(item => item.PanierId == id).Produit.Description;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(produitDescription) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return View("Details");
}
Your RemoveFromCart controller action is decorated with the [HttpPost] attribute meaning that it is ONLY accessible by POST verbs. But in your view you seem to have generated some action link to it:
#Html.ActionLink(
"Enlever du panier",
"RemoveFromCart",
"Panier",
new { id = item.ProduitId },
null
)
But as you are well aware, an Html.ActionLink translates into an <a> tag in your markup which obviously is sending a GET request to the server when clicked.
So basically you have 3 possibilities here:
Use an Html.BeginForm instead of an ActionLink to refer to this action which would allow you to send a POST request
Get rid of the [HttpPost] attribute from your RemoveFromCart action
AJAXify the anchor which would allow you to use a POST request.