Mvc flash message as a partial view - asp.net-mvc

I'm using a FlashHelper to show flash message to users and I need to show partial view istead of default flash message. How can I do that or is that possible or not?.
I need a helper like that:
Flash.Success("_FlashMessagePartial",model)
Or Is there any library you suggest ?

You can't use it like this. If I have understand correct you want to show something like notifications to the users and you don't want your page to be refreshed. The correct answer is that you can do it but it is not correct. Your code will look as a mess you will have a hidden field for the notification and so on. It depends of what you what you want to accomplish. For example:
I am using in my layout a global notification and my snipped looks like this
On the top of the layout just before the
I place an if statement that checks whether error message exists in the TempData
#if(TempData["error"])
{
// here you can visualize it well styled by some template for example
<div class="notification-error">#TempData[error]</div>
}
#if(TempData["success"])
{
// here you can visualize it well styled by some template for example
<div class="notification-error">#TempData[error]</div>
}
Then in your controller if you have something to say to the user you can
just do what you are doing like:
public ActionResult SomeAction(MyModel model)
{
if(something is not valid)
{
this.TempData["error"] user error
return this.View(model);
}
}
That case was if you need some server validation and proper message to the
user. After that option you have to set a script on your layout that removes
the error and success notifications if they exist on the page loads.
The other option if you need some modelstate validation on the client side you can take a look for js-unobtrusive validation that is driven by the viewmodel's attributes and it makes you automatic check on client side before it goes to the server.
The third option is if you need some other notification you can use a JS library called toastr. Examples library url It is light and very easy to use
Hope that this answer is explaining exactly what you need.

Related

mvc notification when record is added

Using a asp mvc system, I would like to perform some kind of user notification that a record was added into the database.
Current paradigm... navPage -> modPage -> datagridPage -> newDatabasePage -> (record added action) This is where it stops, the user is not notified that record is added or failure, it simply reloads the view.
Currently - i am using some text in a viewbag variable after the record was added and based on this value, display a simple javascript message box. But I think there is a better way.
Was thinking that a modal popup implemented through jquery would accomplish this task, but i was educated this was not an optimal solution without using a messaging framework (signalR etc).
Another approach was to use an additional partial page - another partial page????
Any different options that i have missed here would be greatly appreciated.
You can add some beautiful notifications using sweetalert2, here is the documentation
Are you using Bootstrap (or similar)?
Can you not just pass some information into a hidden-as-default alert div?
Assuming you're using EF, when you save an object you can capture the new Id so you can just check for this.
Instead of reloading the view, redirect to the action that creates the initial view and change it so you can pass in the new Id:
int newId = _context.SaveChanges();
return RedirectToAction("GridView", new { Id = newId });
Then change the signature of the Action:
public async Task<ActionResult> GridView(int? Id)
You can then just check if the Id has a value and do something with that information. Then just add that to the ViewModel for the page and display the alert if required:
if (Id.HasValue)
{
viewModel.displayAlert = true;
}
If you don't want to reload the view in full then you can accomplish the same thing using Ajax calls.

Play Framework - Variables in URL instead of as ? parameters

I'm a just starting to learn Play, so this is a basic question, but I've searched every term I can think of and can't find the answer.
All I want to do is have a page that on submit takes an ID from a text field and puts it in the URL directly (e.g. /myservice/person/123). Instead, the URL being generated contains the ID as a parameter (e.g. /myservice/person?id=123).
I know my controller is being invoked correctly if I type the URL in by hand, so I'm inclined to think my routes file is correct. This is what my entry looks like:
GET /person/:id controllers.PersonActions.getPerson(id: String)
So I'm assuming something is going wrong in my template, which looks like this:
#form(routes.PersonActions.getPerson(personID)) {
#* #inputText(personForm("id")) *#
<input type="text" name="id" value="#personID">
<input type="submit" value="Get">
}
You can see that I've commented out another way using #inputText also, but it behaves identically for me. I'm not tied to either method.
I've also tried this using POST, which removes the ID from the URL entirely, which I don't understand either, but since I'm just doing a simple query, I'd rather use GET.
Can anyone help me understand what's going on here? I feel like there's something fundamental about how routing/URLgeneration works that I'm not understanding, but I've gone through the tutorial and the docs so many times today I'm at a loss.
Thanks in advance.
Oh, and I'm using Java 7, Play 2.1, and Eclipse Kepler
I think you are trying to skip a step and map form request data from a view directly to a controller method. You will need to submit the form, have a controller parse the data and then render the next appropriate view based on the data you parsed from the form.
Remember that the personId in your view is a parameter that is bound server-side when the view is rendered. In this case, the submit url of the form is hard coded to whatever personId is passed in to the view at render time -- it doesn't change dynamically when the input box changes.
To fix, add a controller method to accept requests from /person (I'm guessing this based on the part in your question that says the form is being submitted to /person?id=123, in any case it should be the URL of the form you've shown above)
e.g. if you want to use a GET method for the form add:
GET /person controllers.PersonActions.findPerson(id: String)
and in your PersonActions controller (I'm assuming you're using Java, if scala I'm sure you can adapt it from the docs)
public static Result findPerson(String id){
/*
* I'm assuming this method exists and works because you say
* when you type in /person/123 manually the routing works
* and your router says getPerson is the method name for that URL.
*/
return getPerson(id);
}

DriverResult Editor render custom template in Orchard

I'm working over this module (Extended Registration). This module provides a simple way of showing custom user fields in the registration.
Overrides the AccountController form user and loads the Editor Template in the Registration template
AccountController
var shape = _orchardServices.New.Register();
var user = _orchardServices.ContentManager.New("User");
if (user != null) {
shape.UserProfile= _contentManager.BuildEditor(user);
}
return new ShapeResult(this, shape);
Register.cshtml
</div>
#if (Model.OERegister != null) {
<fieldset>
#Display(Model.UserProfile)
</fieldset>
}
<div>
The shape here is the Editor Template (EditorTemplate/Parts/template)
It Works just fine, but I need to hide some fields from the registration form.
I'm kind of lost here, and I want to do it in the most Orchish way.
Thanks in advance.
As far as I understand the question here is how to generally hide some fields from a form.
Depending on how the author of the form's code designed it or whether you're the developer, there are multiple ways:
Have parts of the form in separate shapes, and return their factories in a Combined driver result from a driver. This means, your driver building part of the form by providing the shapes for a part's editor will register multiple shapes (this is similar to what e.g. BodyPartDriver.Display() does: it returns three separate shape registrations). Now these can be individually controlled by placement, so you can also hide them.
If you have no such fine control over how the form is built, you can still override the shape templates containing the fields you want to hide. Then in the override you can freely customize the look of the form. Beware that unlike the first solution, this won't automatically prevent the user from posting the hidden fields' data to the server, and thus saving it.
BTW I don't think the ContentManager.New() can ever return null. Even if the content type is not statically defined (i.e. created from a migration or through ContentDefinitionManager) it will return a content item.

Changing text if a form has an error

I currently have a summary message at the top of my form, inviting my user to login. If the form does not validate on submit, I wish for this to then be replaced with the relevant error.
The only way I can think of is by hiding the initial text (perhaps in a #Html.Label) and then showing a #Html.ValidationSummary. However, I feel there is most likely a far more efficient way of doing this.
Can anybody help?
I would have an #Html.Label helper, and use the ViewBag object to pass data to it. That way in your controller when you test for ModelState.IsValid, if that is false you can set the ViewBag property so that it passes to the label helper.
Make sense? That's how I'd do it.
turn on the validation summary
#Html.ValidationSummary(true)
in your post ActionResult check the ModelState
[HttpPost]
public ActionResult Foo( Bar _bar){
if(ModelState.IsValid){
//noral course of action
return RedirectToAction("Foo"); //Redirect to the GET method
}
ModelState.AddModelError("", "|Your Message Here");
return View(_bar);
}
No, there is no problem with the approach.
I generally use single div with jquery for the stuff like form validation etc.
I create a single div on page where any kind of message can be displayed for user guideance.
ex:
if I've display some kind of information to user, it will be displayed as following:
div id='divMessage'</div>
$('#divMessage').html('Please fill the following form.').removeClass().addClass('msg');
While in case of some error same div will be used to display the error message:
$('#divMessage').html('some error occurred.').removeClass().addClass('errmsg');
I hope till will be of any use.

How to keep views free of authorization logic in mvc?

I have a view to display a list of items.
The user can edit, delete or create new items, but according to their authorizations they may or may not be allowed to do some of this actions.
I have the requirement to display only the actions which the current user is allowed to do, but I don't want to clutter the views with authorization if-else's
Despise of being a very common requirement, I can't find a real satisfactory way of doing it.
My best approach so far is to provide an overload to the Html.ActionLink extension method that takes the permission to ask for, but there are going to be more complex scenarios, like hiding entire blocks of html or switching a textbox for a label+hidden.
Is there a better way to do this?
One example I can think of would be to invoke Html.RenderAction (link: http://msdn.microsoft.com/en-us/library/ee703490.aspx), and then pass the link you wish to use as a route value to the action method (it will appear as a parameter on your action). Because it's a RenderAction, you get to go back through the controller process and thus you can have it render whatever view or data you want depending on the user's state.
Example:
<% Html.RenderAction("Permissions" /* Controller */, "PermissionLink", new { Url = "Admin.aspx" }); %>
And your controller would have something like:
public ActionResult PermissionsLink (string url)
{
// Do Whatever kind of Authentication you want here, Session is available, etc
if(authenticated)
return View("Link");
else
return View("Blank");
}
I personally don't see anything wrong with this kind of conditional logic within the view. The logic is still all about presentation. You decide whether to show or hide, enable or disable, highlight etc. This is the view's job, not the controller's. As long as the view does not need to actually compute anything to come to its decision. The controller should be agnostic of the view's implementation as much as the other way around.
My approach would be this:
Make the controller do the actual logic of deciding the level of access that the user has
Pass this information to the view using (ie via the ViewModel) but in a way that is neutral to implementation details (ie "user is admin", "user is an author", etc)
Let the view draw itself appropriately using only the pre-compiled data that is provided by the controller.
This also has the benefit that the view itself can be removed and replaced without any effect on the controller.
We had this same issue. We ended up writing a lot of helper methods and in cases where lots of html output was required, we put them in partial views.
Would it not be simpler to create several views with various controls based on what values the user can change, then return the right view based on the user's access rights?
Views should be for presenting information only, there really shouldn't be any conditional logic contained in them, or at least a bare minimum.
I've always found when i get to the point where i'm finding it hard to grok a situation like yours, the best solution is always to go back to the controller and e-assess what i'm passing to the view in the first place.
By the time the View is called to do its job, all of the important 'decisions' should have already been made.
In complicated situations where are many conditions and rules I'm doing this that way:
ViewModel
public class ModelView
{
private IAuthorisationService { get; set; }
public bool CanShow
{
...
}
}
View:
<% if(Model.CanShow) { %>
<html>
<% } %>

Resources