Controller:
public ActionResult Delete(int id)
{
Student _std = new Student();
var abc = _dbcon.StudentList.Where(c => c.Roll_ID.Equals(id)).SingleOrDefault();
_dbcon.StudentList.Remove(abc);
_dbcon.SaveChanges();
return View("Test");
}
This is my view and the error comes at foreach loop
View:
#foreach (StudentViewModel _EachStd in #Model.StudentList)
{
<tr>
<td> #_EachStd.Roll_ID</td>
<td> #_EachStd.Name</td>
<td> #_EachStd.Maths</td>
<td> #_EachStd.Urdu</td>
<td> #_EachStd.English</td>
<td>#_EachStd.ObtainNumber</td>
<td>#_EachStd.Percentage</td>
<td> #_EachStd.Grade</td>
<td>#Html.ActionLink("Edit", "Edit", "Home", new {id= #_EachStd.Roll_ID },null)</td>
<td>#Html.ActionLink("Delete", "Delete", "Home", new { id = #_EachStd.Roll_ID }, null)</td>
</tr>
}
</tbody>
</table>
I got Null Error exception, but after refresh i got the record delete. But why the error occur I dont get It.Whenever i run this code my Edit controller is working correctly but my Delete controller is not working correctly, and error is occur like there is "Null erroe exception"
error is occur like there is "Null erroe exception"
You mean a NullReferenceException? That would mean something is null that you're trying to use as though it has a value.
This is my view and the error comes at foreach loop
So then something on this line is null?:
#foreach (StudentViewModel _EachStd in #Model.StudentList)
The only thing you're trying to dereference on that line is Model. So it follows that Model is null. Are you passing a model to your view?
return View("Test");
No, you are not. You need to pass a model to your view in order to use that model within your view.
As an aside, returning a view from this delete operation probably isn't the way to go in the first place. Consider that the user would now be on the URL /Home/Delete and viewing it as a page. This would quickly get confusing for both the user and your code.
Instead of returning a view, especially one without a model, redirect the user to the action which builds the model and displays the view. Which in your code could be something as simple as:
return RedirectToAction("Test");
Related
I am working on Laravel 5.5 framework.
I have a form home page like this:
<form action = "/result" method = "post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token() ?>">
<table>
<tr>
<td>Name or Nickname</td>
<td><input type = "text" name = "name_nickname" autofocus /></td>
</tr>
<tr>
<input type = "submit" value = "LuckyNumber" />
</td>
</tr>
</table>
The controller looks like this:
class SixGetController extends Controller
{
public function luckyNumber(Request $request){
$nameNickname = $request->input('name_nickname');
$luckyNumber = rand (1,10);
DB::table('visitor')->insert(
['name_nickname' => $nameNickname, 'luckyNumber' => $luckyNumber]);
return view('result', ['nameNickname' => $nameNickname, 'luckyNumber' =>
$luckyNumber]);
}
The result page looks like this:
<p><?php echo $nameNickname; ?> </p>
<p>Your lucky number is <?=$result?> .</p>
If the user presses the reload F5 button the scrip will reroll the random number generator and resubmit the data with the rerolled number. I've read about the PGR pattern which i dont know how to use and something about manipulating history which i dont understand either. Can somebody point out what kind of code do i put somewhere to prevent the reroll and the resubmission. Thanks.
For laravel implementation, you can use Session Flash Data.
Sometimes you may wish to store items in the session only for the next
request. You may do so using the flash method. Data stored in the
session using this method will only be available during the subsequent
HTTP request, and then will be deleted. Flash data is primarily useful
for short-lived status messages:
In this case, when someone make a post request, you should store the useful data to session, and redirect them to other route. The other route can then retrieve the useful data to display to the view, and user no longer resubmit the form when refresh the page.
public function luckyNumber(Request $request) {
...
$request->session()->flash('nameNickname', $nameNickname);
$request->session()->flash('luckyNumber', $luckyNumber);
return redirect()->action('SixGetController#resultView');
}
public function resultView(Request $request) {
$nameNickname = $request->session()->get('nameNickname');
$luckyNumber = $request->session()->get('luckyNumber');
return view('result', ['nameNickname' => $nameNickname, 'luckyNumber' => $luckyNumber]);
}
I have a main view and the URL for this view has a Action/Controller/Area and id value, something like:
http://localhost:56513/Incident/IncidentHome/Index/8c02a647-a883-4d69-91be-7ac5f7b28ab7
I have a partialview in this main view, one that calls methods in the controller via Ajax. This partial view needs to know the ID value of the url for the parent page. I found how to do this is through 'ParentActionViewContent'. Something like:
using (Ajax.BeginForm("UpdatePersonalStatusPanel", "Status", new { area = "Tools" , id = ViewContext.ParentActionViewContext.RouteData.Values["id"].ToString() }, new AjaxOptions { UpdateTargetId = "divPersStatus" }))
{
<p style="text-align: center;">
<span class="editor-label">#Html.LabelFor(m => m.StatusText)</span> <span class="editor-field">#Html.EditorFor(m => m.StatusText)</span>
<input type="submit" value="Change Current Status" />
</p>
}
Now, this works fantastic for calling the controller method. The ID is passed correctly so that the controller can then see it in the routedata. I use the id to perform a database call, and then return the partialview again. The problem is on the return. I get a 'Object reference not set to an instance of an object' on the ViewContext.ParentActionViewContext.RouteData.Values["id"].ToString() bit in the ajax.beginform , and my targetid doesn't refresh.
Clearly I must be doing something wrong. Does someone else have a better way to see the parent view's routedata through Ajax?
If I'm understanding you correctly, this partial view calls itself. So ParentActionViewContext works the first time because the first time your main view calls an action using this partial view. However, later an ajax call directly returns this partial view. When the partial view is invoked directly there is no Parent View action hence the null reference on ParentActionViewContext.
Rather than deal with with route data I recommend including the id in the model of your partial view.
new { area = "Tools" , id = Model.Id }
I'm working on a Nopcommerce, and need to generate Invoice (custom made not as what they already provide, because it just doesn't solve our purpose). We need to generate Invoice
in new tab(using another cshtml file) using Controller's method also I'm passing model data on view.
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.ProbableDeliveryDate):
</td>
<td class="adminData">
#Html.EditorFor(model=>model.ProbableDeliveryDate)
</td>
</tr>
<tr>
<td>
#if(Model.CanGenrateInvoice)
{
<input type="submit" name="generateinvoice" value="#T("Admin.Orders.Fields.generateinvoice")" id="generateinvoice" class="adminButton" />
}
</td>
</tr>
I've to post data to get value of probableDeliveryDate to controller method and after that want to open view in new tab.
How can i do this?
If you are getting to the action from the first page via an Html.ActionLink you can do this:
Html.ActionLink("Open Invoice", "ActionName","ControllerName", new { id = Model.InvoiceID }, new { target = "_blank" });
Specifying target = "_blank" will open in the new tab
Update
Since you are posting the model to the controller (I was hoping RedirectToAction could help open a new window/tab but that doesn't look to be the case)
My spidy sense is tingling on the flow you have tho... This is just me but I would do something a little different.. such as
Post the model to the controller
Save the data that generates the invoice
Return the InvoiceID to the action
Add the InvoiceID to the model
Send the model back to the view
Inform the user that
the invoice was generated and show a link - like above - that allows the user to open the invoice OR
this provides the perfect clean solution to show model errors if there were any
Your view could have a piece of razor code that did that:
#{
if(Model.InvoiceID != null && Model.InvoiceID !=0) {
#Html.ActionLink("Open Invoice", "ActionName","ControllerName", new { id = Model.InvoiceID }, new { target = "_blank" });
}
}
I know this sound somewhat off-piste but how would you create a weakly typed view where you pass in a collection of objects and iterate in razor accordingly and display in a table?
-- Controller View --
???
-- Razor View ---
#foreach (var item in Model)
{
<tr>
<td>
#item.attr1
</td>
<td>
#item.attr2
</td>
</tr>
}
Frist you know the data send
From Controller -------> view by two way
By weak type view
and by strong type view
there is no other way of passing data from controller to view ...(remember)
what is intelliscence ----> which show the related sub property of any model
like we write Model. --------> then all property show in
droupdown list after dot(.).
A.what is weak type view
This is used without using model i.e like using ViewBag and other.
There is no intellisence for this type of view and it is complicated, and when you write
any name which not exist then it give at runtime error.
Ex.
.............Controller
ViewBag.List = List<job>;
return View();
.............Razor View
#foreach(var item in ViewBag.List)
{
// when you write no intellisence and you want to write your own correct one...
#item.
}
B. What strongly type view
this is used model to send data from controller to view an vice-versa.
Model are strongly typed to view so, it show intellicence and when you write wrong
then there only error show at compile time..
Ex.
.................Controller
List<job> jobdata =new List<job>();
return View(jobdata);
................view
//Mention here datatype that you want to strongly type using **#model**
#model List<job>
#foreach(var item in Model)
//this **Model** represent the model that passed from controller
// default you not change
{
#item. //then intellisence is come and no need write own ....
}
that is weak and strong type view ......
So now you solve any problem with this basic.....
may I hope it help u....
But it is best to use Strongly Typed view so it become easy
to use and best compare to weak...
#model dynamic
Will do what you want, I believe.
If its going to be a collection, then maybe use
#model ICollection
It's not weakly typed. It's typed to a collection of some kind.
#model IEnumerable<MyClass>
OK, late to the party I know, but what you're after is a view stating "#model dynamic" as already stated.
Working Example: (in mvc3 at time of posting)
NB In my case below, the view is actually being passed a System.Collections.IEnumerable
As it's weakly typed, you will not get intelesense for the items such as #item.Category etc..
#model dynamic
#using (Html.BeginForm())
{
<table class="tableRowHover">
<thead>
<tr>
<th>Row</th>
<th>Category</th>
<th>Description</th>
<th>Sales Price</th>
</tr>
</thead>
#{int counter = 1;}
#foreach (var item in Model)
{
<tbody>
<tr>
<td>
#Html.Raw(counter.ToString())
</td>
<td>
#item.Category
</td>
<td>
#item.Description
</td>
<td>
#item.Price
</td>
</tr>
#{ counter = counter +1;}
</tbody>
}
</table>
}
Edit: removed some css
I think I just need someone to show me the obvious.
I have a spark partial
_MessageItem.spark
that is used within a view
like so
<for each="var m in messageList">
<MessageItem message="m"/>
</for>
the partial looks like this:
<tr id="${message.MessageId}">
<td >${message.CreateDate.ToString("M/d/yy h:mm")}</td>
<td >
<b>${message.Subject}</b>
</td>
<td >${message.FromUser.FullName}</td>
<td >${message.ToUser.FullName}</td>
</tr>
<tr>
<td/>
<td colspan="3">${message.Body}</td>
</tr>
works like a champ, except when I try and call the partial directly from an action like so:
public ActionResult GetMessage(Message message)
{
return PartialView("MessageItem",message);
}
When I do the above I get
error CS0103: The name 'message' does not exist in the current context
So my current solution is to create a wrapper partial that feeds the MessageItem partial
like so:
_ActionMessageItem.spark:
<MessageItem message="(Message)ViewData.Model"/>
So can someone state the obvious and tell me how to modify
1) Modify my MessageItem partial so whether being called from PartialView() or within a .spark file it will work
2) Tell me how I need to modify my Controller Action so it won't throw an exception
<viewdata model="Message" message="Message" />
<var msg="message ?? Model" />
Then use the msg variable instead of message (like, ${msg.Subject}, etc).
You may also have luck with adding single
<default message="Model" />
but the first way is the one I think will work.
When you pass parameters PartialView, spark doesn't know anything about your parameter name, only the value that was passed in. So, it uses the name of the argument, which I believe it is model. Since your code is looking for the parameter message it throws an error. I think one solution might be to change to something like this:
<MessageItem model="(Message)ViewData.Model"/>
model may be cased as Model, you'll have to guess and check.
try to call the partial with the underscore and an anonymous object.
ViewData["message"] = message;
return PartialView("_MessageItem");
the problem is that when you call it from the action you're passing data as a Model, but when calling from another view you're passing the data as a parameter. you could only use your data as Model if the other view also shares the same Model object type.
otherwise, what I'd do is pass it in ViewData in your Action:
public ActionResult GetMessage(Message message)
{
ViewData["message"] = message;
return PartialView("MessageItem");
}