i'm problem with Net Fiddle use MVC. When i click the button "Ordernar por Nome" result in Erro page, but in my PC works well.
https://dotnetfiddle.net/HCLpdv
The problem code is:
[HttpGet]
public ActionResult Index()
{
listPessoas = new List<Pessoa>();
populatePessoas(listPessoas);
CountSituacao();
ViewData["pessoas"] = listPessoas;
return View();
}
[HttpGet]
public ActionResult OrderByName()
{
OrderList();
ViewData["pessoas"] = listPessoas;
return View("Index");
}
My problem is that when Net Fiddle executes OrderByName action it says that it can't find view
Thanks!
I would say that this is a specific of Net Fiddle as we don't have actual file system there and it has only one view. And UI doesn't allow to specify name for that view.
We treat view name dynamically based on current action name. In your case you have two actions Index and OrderByName, so if both methods will use default View() without specifying viewName, then it will be working fine as by default we render view based on current executing action.
It's not so correct behavior, but otherwise we need ability to specify a couple of views with names, that we can't do right now.
So to fix your issue you just need to use such action code:
[HttpGet]
public ActionResult OrderByName()
{
OrderList();
ViewData["pessoas"] = listPessoas;
return View("OrderByName");
}
Or just empty View()
Related
I have two methods:
public ActionResult EditNote(int? id)
{
NotesModel edit = NotesProcessor.LoadNote(Convert.ToInt32(id));
if (edit.Author != Session["UserName"].ToString())
{
edit.Id = null;
edit.Title = null;
edit.Note = null;
edit.Author = null;
return View(edit);
}
return View(edit);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditNote(NotesModel model)
{
if(model.Id == null) NotesProcessor.SaveNoteEdit(model);
else
{
model.Author = Session["UserName"].ToString();
NotesProcessor.SaveNote(model);
}
return View();
}
I've simplified the code to only show the problematic part which is:
A logged in user is trying to edit a note which they're not allowed to because it was made by another user. So all the values are set to null so the user will create a new note. The first method will receive an id to search the database for the note the user is trying to edit.
In the next HttpPost method however model.Id is still the same as the integer received by the first method despite changing all the values to null in the first method.
The first method is called from the views page like this:
#Html.ActionLink("Edit", "EditNote", new { id = Model.Id })
Anyone got an idea whats going on here?
You are actually not posting anything to the system as it seems, you are just calling the HttpGet method via URL and then clearing out the view model data at page level only. So, it seems your HttPost method is not even hitting. Try debugging and see whether your HttpPost method gets hit.
You don,t even need to create two methods for what you want to achieve. All you need is just single HttpPost method.
For HtpPost method to be called, you need to either create Form control at UI level with action type as post or you need to hit HttpPost method via JavaScript / JQuery
I hope this helps.
I have a Controller with some actions on it as follows:
[HttpPost]
public ActionResult Create(CreateModel model)
{
if (model.SelectedCustomers.Count > 0 &&
model.SelectedVersions.Count > 0 &&
!string.IsNullOrWhiteSpace(model.ScriptName) &&
!string.IsNullOrWhiteSpace(model.ScriptText))
{
Script script;
...save to database...
return Edit(script.Id); //<---------Return other view here
}
else
{
...
}
}
[HttpGet]
public ActionResult Edit(int? scriptId)
{
return View();
}
After the Create action runs, and saves my model to the database successfully, I want to send the user to the Edit view for the newly created script. When I use the code above, specifically return Edit(script.Id); it just sends the user back to the Create view instead of the Edit view. When the user navigates to the Edit action directly, or through the result of an Html.ActionLink pointed at Edit everything works correctly.
What am I doing wrong?
This isn't doing what you think it does:
return Edit(script.Id)
It's not actually telling the framework to go to that action. It's just returning the return value of that method. Purely a C# concern before any components of the ASP.NET MVC Framework are involved at all. And what is that return value:
return View()
So the former is really functionally the same thing as the latter. And any time you use return View() in ASP.NET MVC, the framework will determine that view by examining the action currently being called, which in this case is Create.
What you want isn't to return the Edit view (even if you do, in this case, the user is still on the Create URL, which will cause confusion). What you want is to return a redirect to tell the client to request that next action:
return RedirectToAction("Edit", new { scriptId = script.Id });
You can always call RedirectToAction and return that action result. That will inform the browser to redirect to the different action.
I think you will need something like this:
return RedirectToAction("Edit", new { scriptId = script.Id });
Calling Edit directly is no different than calling a method.
You can do with this RedirecToAction with input parameters.
return RedirectToAction("Action", new { id = 12 });
In Your Case:
return RedirectToAction("Edit", new { scriptId = script.Id });
What am I doing wrong with my MVC code here ? The Index view includes a form that submits to itself, what I'd like is the controller to process the submitted form and then return to the View.
What actually happens is the form is processed correctly, but the View returned is as if nothing happen (e.g. ids that have been deleted are still shown). If I manually refresh the page though, it displays correctly again. I don't think it's broswer caching related, as redirecting to the same view from a different controller works fine. How can I fix it ?
public ViewResult Index()
{
return View(GetComments());
}
[HttpPost]
public ActionResult Index(int[] AllIds)
{
if (AllIds != null)
{
foreach (int id in AllIds)
{
// do stuff
}
}
return RedirectToAction("Index");
}
Edit: When submitting the form, the breakpoint on the first method is not hit and trying to "Step Into (F11)" the return RedirectToAction("Index"); line just moves straight onto the final } instead.
Install Fiddler or Firebug for Firefox and watch the traffic, see it it really returns a new response or a HTTP 304 from the browser(cached page). If everything checks out then you have a problem with your db persistence and or queries.
Have you tried this? I'm wondering, depending on how you persist the data, if it's not being saved until after the server returns a response..?
public ViewResult Index()
{ // breakpoint
var comments = GetComments(); // debug and inspect the value of this variable
return View(comments);
}
[HttpPost]
public ActionResult Index(int[] AllIds)
{
if (AllIds != null)
{
foreach (int id in AllIds)
{
// do stuff
}
}
return RedirectToAction("Index"); // breakpoint
}
I know some people use an IUnitOfWork in MVC that only calls SaveChanges / Commit on the ORM at the end of the request. Is it possible that the // do stuff removes items from the collection, but does not persist to the db until AFTER the GET Index() is returned?
Update
Instead of return RedirectToAction("Index"), have you tried RedirectToAction(Index())?
Try entering controller name as well. That helped me. For example:
return RedirectToAction("Index","Home");
I am absolute beginner in C#, ASP.NET and MVC2 and this means that I just might be missing something exceptionally basic. I tried to search for it, but here again, I failed to come up with the proper incantations for neither Google not StackOverflow, so here comes the question:
I am trying to create a basic controller with two actions:
[HttpPost]
public ViewResult Create(CustomerCreateData data)
{
CustomerRecord cr = //create customer record from input data...
return RedirectToAction("Details");
}
public ViewResult Details(int id)
{
CustomerRecord cr = // load customer record with specified id...
return View(cr);
}
My idea is thet after successful POST /Customer/Create the user would be redirected to GET /Customer/Details/42 where 42 is id of the newly created customer record.
What is the proper incantation for this in ASP.NET MVC2
PS - I've seen countless examples of redirecting to "Index" action, but that is not quite enough.
You can pass data to the RedirectToAction method:
return RedirectToAction("Details", new { id = cr.Id });
This is assuming you either have a defined route, e.g. Customer/Details/{id} or that you still have the default route {controller}/{action}/{id}.
In Create ActionResult, after creation success make an action like this (or realy this for example):
return RedirectToAction("Details", new { Id = cr.Id });
This code produce a redirect to Details/id/{cr.Id}.
Sorry for bad english (i'm italian)
Okay so, i am totally new to MVC and I'm trying to wrap my head around a few of the concepts. I've created a small application...
This application has a view for creating a new Individual record. The view is bound to a model ViewPage... And I have a associated IndividualController which has a New method...
The New method of the IndividualController looks like this...
public ActionResult New()
{
var i = new Individual();
this.Title = "Create new individual...";
i.Id = Guid.NewGuid();
this.ViewData.Model = new Individual();
return View();
}
Now, the above all seems to be working. When the view loads I am able to retrieve the data from the Individual object. The issue comes into play when I try and save the data back through the controller...
In my IndividualController I also have a Save method which accepts an incoming parameter of type Individual. The method looks like...
public ActionResult Save(IndividualService.Individual Individual)
{
return RedirectToAction("New");
}
Now, on my view I wanted to use a standard html link/href to be used as the "Save" button so I defined an ActionLink like so...
<%=Html.ActionLink("Save", "Save") %>
Also, defined in my view I have created a single textbox to hold the first name as a test like so...
<% using (Html.BeginForm()) { %>
<%=Html.TextBox("FirstName", ViewData.Model.FirstName)%>
<% } %>
So, if I put a break point in the Save method and click the "Save" link in my view the break point is hit within my controller. The issue is that the input parameter of the Save method is null; even if I type a value into the first name textbox...
Obviously I am doing something completely wrong. Can someone set me straight...
Thanks in advance...
Your New controller method doesn't need to create an individual, you probably just want it to set the title and return the view, although you may need to do some authorization processing. Here's an example from one of my projects:
[AcceptVerbs( HttpVerbs.Get )]
[Authorization( Roles = "SuperUser, EditEvent, EditMasterEvent")]
public ActionResult New()
{
ViewData["Title"] = "New Event";
if (this.IsMasterEditAllowed())
{
ViewData["ShowNewMaster"] = "true";
}
return View();
}
Your Save action should take the inputs from the form and create a new model instance and persist it. My example is a little more complex than what I'd like to post here so I'll try and simplify it. Note that I'm using a FormCollection rather than using model binding, but you should be able to get that to work, too.
[AcceptVerbs( HttpVerbs.Post )]
[Authorization( Roles = "SuperUser, EditEvent, EditMasterEvent")]
public ActionResult Save( FormCollection form )
{
using (DataContext context = ...)
{
Event evt = new Event();
if (!TryUpdateModel( evt, new [] { "EventName", "CategoryID", ... }))
{
this.ModelState.AddModelError( "Could not update model..." );
return View("New"); // back to display errors...
}
context.InsertOnSubmit( evt );
context.SubmitChanges();
return RedirectToAction( "Show", "Event", new { id = evt.EventID } );
}
}
If I don't create a new Indvidual object in the New method then when my view tries to bind the textbox to the associated model I get a NullReferenceException on the below line in my view...
`<%=Html.TextBox("FirstName", ViewData.Model.FirstName)%>`
With regards to the Save method. From what I understand since my view is strongly typed shouldn't I be able to have a method signature like...
`public ActionResult New(IndividualService.Individual ind)
{
return View();
}`
I thought that was the purpose behind model binding..?
I would strongly recommend that you take a step back from what you are doing and run through some of the Tutorials/Videos here http://www.asp.net/learn/
If you have a strongly typed View it means that when the Controller picks that view to generate the output the view has better access to the Model.
However the View is not responsible for what comes back from the client subsequently such as when a form is posted or a URL is otherwise navigated to.
ASP.NET-MVC uses information in the URL to determine which Controller to hand the request off to. After that it's the controller's responsibility to resolve the various other elements in the request into instance(s) of Model classes.
The relationship between the incoming request and the controller is clouded by the significant assistance the ASP.NET-MVC routing gives the controller. For example a route can be defined to supply parameters to the controller method and thats all the controller needs and hence you don't see any code in the method relating to the http request. However it should be understood that the contoller method is simply processing a http request.
I hope you can see from the above that it would be too early in a requests life-cycle for an instance of a class from the model to passed to a public method on a controller. Its up to the controller to determine which model classes if any need instancing.