Remote Validation is Not Being Hit - remote-validation

I'm trying to use remote validation to make sure an input has a value but only when a previous input has a specific value. However, the remote validation is not being hit.
I have put a break point on the remote validation action in the controller and that is never hit.
This is in my model:
[Remote("_Validate_Show", "Validation", AdditionalFields = "Group_Id,Dev_Group_Id", ErrorMessage = "Please select an option")]
public bool? Show { get; set; }
This is my controller:
public class ValidationController
{
public JsonResult _Validate_Show(bool? Show, Guid? Group_Id, Guid Dev_Group_Id)
{
if (!Show.HasValue && Group_Id.HasValue && Group_Id == Dev_Group_Id)
{
return base.Json(false, JsonRequestBehavior.AllowGet);
}
return base.Json(true, JsonRequestBehavior.AllowGet);
}
}
And this is what I have in my View:
<div>#Html.ExtendedDropDownListFor(model => model.Group_Id, Model.Group_Ids)</div>
<div>#Html.DropDownListFor(model => model.Show, Model.Show_Options)</div>
<div>#Html.ValidationMessageFor(model => model.Show)</div>
Basically if the 'Group_Id' is the 'Dev_Group_Id' then 'Show' must have a value but if the 'Group_Id' is not the 'Dev_Group_Id' then 'Show' can be null.
I even tried to simplify it and remove the additional fields so it just checked the 'Show' value but again the action in the controller was never hit.
I can also confirm that I have these scripts in my view:
<script src="#Url.Content("~/Scripts/jquery.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>

Your _Validate_Show is get only and remote validation uses post. Add [AcceptVerbs("Get", "Post")] to the method viz:
[AcceptVerbs("Get", "Post")]
public JsonResult _Validate_Show(bool? Show, Guid? Group_Id, Guid Dev_Group_Id)
{
if (!Show.HasValue && Group_Id.HasValue && Group_Id == Dev_Group_Id)
{
return base.Json(false, JsonRequestBehavior.AllowGet);
}
return base.Json(true, JsonRequestBehavior.AllowGet);
}

Related

How to redirect using equals and question mark as characters of the argument in redirectToAction()?

I want to redirect the user to another page in my asp.net mvc webapp using
return RedirectToAction("foo?productId=" + product.id);
but it redirects the user to
foo%3fproductId%3dproduct.id
I want the app to redirect the user to
foo?productId=product.id
so the app is able to use the product.id value
Use this overload of RedirectToAction:
return RedirectToAction("foo", new { productId = product.Id });
//How to use RedirectToAction with additional param in MVC
return RedirectToAction("actionName", "ControllerName", routevalue);
RedirectToAction with parameter:
return RedirectToAction("ActionName","controllerName", new {#productId=product.id});
For Example
If one want to Show error message for [httppost] then he/she can try by passing an ID using
return RedirectToAction("foo", "YourControllerName", new { #productId= product.id});
for Details like this
public ActionResult foo(int? productId)
{
if (productId> 0)
{
ViewBag.Status = productId + " item is in use";
}
return View();
}
[Httppost]
public ActionResult LogIn(FormCollection form)
{
string user= form["UserId"];
string password = form["Password"];
if (user == "admin" && password == "123")
{
return RedirectToAction("Index", "Admin");
}
else
{
return RedirectToAction("foo", "YourControllerName", new { #productId= 1 });
}
}
Hope it works fine.

ASP.Net Web API Action Result

I'm building an ASP.Net Web API application and i have the following code...
public IHttpActionResult GetCustomers() {
var customers = context.Customers.ToList();
return Ok(customers);
}
I'm using the Ok() method to return customers because i'm using an IHttpActionResult return type.
Now if i have the following method
public void DeleteCustomer(int id) {
var customerInDb = context.Customers.SingleOrDefault(c => c.Id == id);
if (customerInDb == null) {
NotFound();
}
context.Customers.Remove(customerInDb);
context.SaveChanges();
}
Can I use NotFound() method here when the return type of my ActionMethod is void???
Void does not have a return type. So you can try to call NotFound(), but I'm not sure if this would even compile - Haven't tried. Why don't you just go with an out of the box IHttpActionResult?
public IHttpActionResult DeleteCustomer(int id)
{
var customerInDb = context.Customers.SingleOrDefault(c => c.Id == id);
if (customerInDb == null)
{
return NotFound();
}
context.Customers.Remove(customerInDb);
context.SaveChanges();
return Ok(customerInDb);
}
Using IHttpActionResult is the more elegant version. If the id is invalid, you can just safely exit your method and tell the calling client that something went wrong. If everything went well, you're just giving the client a thumbs-up. IF you return your deleted entity or just an empty Ok() should not matter at this point.
Using void may or may not delete the entity in your data storage. The client would never know, because the server would not return any response.

MVC4 - ContextDependentView - What does it mean?

I have just started using MVC4 and the first action method that I look at has something new. I checked out the internet and can't find anything about this:
public ActionResult LogOn()
{
return ContextDependentView();
}
Does anyone know what a ContextDependentView is ?
Something new to me.
It's purpose is to facilitate View or PartialView action results for the Login and Register actions.
private ActionResult ContextDependentView()
{
string actionName = ControllerContext.RouteData.GetRequiredString("action");
if (Request.QueryString["content"] != null)
{
ViewBag.FormAction = "Json" + actionName;
return PartialView();
}
else
{
ViewBag.FormAction = actionName;
return View();
}
}
Like other things in MVC it is done by convention... the convention here is when the Request.QueryString contains a ?content=xxxx, it prepends "Json" to the action name, stuffs it a ViewBag property and returns the partial version of the View. For example:
A request for /Account/Login?content=test would be resolved to ViewBag.FormAction = "JsonLogin"; and then return a partial.
A request for /Account/Login has no content query string so its form action remains ViewBag.FormAction = "Login";

RedirectToAction usage in asp.net mvc

I want to post some questions about ASP.Net MVC. I am not familiar with web developing, But I was assigned to the web part of a project. We are doing the following: first, we create get & set properties for the person data:
public class Person
{
public int personID {get;set;}
public string personName {get;set;}
public string nric {get;set;}
}
and after login, we put the data in a class Person object and we use RedirectToAction like this:
return RedirectToAction("profile","person",new { personID = Person.personID});
It's working normally, but the parameter are shown in the URL. How can I hide them and also
can I hide the action name? Guide me the right way with some examples, please.
The parameter are shown in the URL because that is what the third parameter to RedirectToAction is - the route values.
The default route is {controller}/{action}/{id}
So this code:
return RedirectToAction("profile","person",new { personID = Person.personID});
Will produce the following URL/route:
/Person/Profile/123
If you want a cleaner route, like this (for example):
/people/123
Create a new route:
routes.MapRoute("PersonCleanRoute",
"people/{id}",
new {controller = "Person", action = "Profile"});
And your URL should be clean, like the above.
Alternatively, you may not like to use ID at all, you can use some other unique identifier - like a nickname.
So the URL could be like this:
people/rpm1984
To do that, just change your route:
routes.MapRoute("PersonCleanRoute",
"people/{nickname}",
new {controller = "Person", action = "Profile"});
And your action method:
public ActionResult Profile(string nickname)
{
}
And your RedirectToAction code:
return RedirectToAction("profile","person",new { nickname = Person.nickname});
Is that what your after?
If you don't want the parameter to be shown in the address bar you will need to persist it somewhere on the server between the redirects. A good place to achieve this is TempData. Here's an example:
public ActionResult Index()
{
TempData["nickname"] = Person.nickname;
return RedirectToAction("profile", "person");
}
And now on the Profile action you are redirecting to fetch it from TempData:
public ActionResult Profile()
{
var nickname = TempData["nickname"] as string;
if (nickname == null)
{
// nickname was not found in TempData.
// this usually means that the user directly
// navigated to /person/profile without passing
// through the other action which would store
// the nickname in TempData
throw new HttpException(404);
}
return View();
}
Under the covers TempData uses Session for storage but it will be automatically evicted after the redirect, so the value could be used only once which is what you need: store, redirect, fetch.
this may be solution of problem when TempData gone after refresh the page :-
when first time you get TempData in action method set it in a ViewData & write check as below:
public ActionResult Index()
{
TempData["nickname"] = Person.nickname;
return RedirectToAction("profile", "person");
}
now on the Profile action :
public ActionResult Profile()
{
var nickname = TempData["nickname"] as string;
if(nickname !=null)
ViewData["nickname"]=nickname;
if (nickname == null && ViewData["nickname"]==null)
{
throw new HttpException(404);
}
else
{
if(nickname == null)
nickname=ViewData["nickname"];
}
return View();
}
Temp data is capable of handling single subsequent request. Hence, value gone after refresh the page. To mitigate this issue, we can use Session variable also in this case. Try below:
public ActionResult Index(Person _person)
{
Session["personNickName"] = _person.nickName;
return RedirectToAction("profile", "person");
}
And in "profile" actionmethod:
public ActionResult profile()
{
Person nickName=(Person)Session["personNickName"];
if(nickName !=null)
{
//Do the logic with the nickName
}
}

Message Control in Masterpage with ASP.NET MVC

Hey everyone. Got a custom on how to do this as im new to MVC and trying to get a couple of small things implemented. This is the way I did it in WebForms but want to transition it to MVC.
I have a user control that contains CSS which will render a message. This control is located in the MasterPage and called from a ASPX page like this:
Pseudo code:
try{
Msg.MessageMode = WebPageMessageMode.OK;
Msg.ShowOK("Report deleted.");
}
catch
{
Msg.MessageMode = WebPageMessageMode.ErrorMessage;
Msg.ShowError("There was a problem deleting the report.");
}
Masterpage.aspx
<cc1:WebPageMessage runat="server" ID="msg" />
I currently have the control in the MasterPage and now im a bit confused about proceeding from here.
Should I put the 'Msg' object above from the pseudo code to a View from the MasterPage?
What is the proper way to do something like?
I dont think there is a one-solution-fits-all here.
Anyway this is my solution that uses jQuery:
1) Create a MyResultModel class to handle a message to the user
public enum MyResultType { Info, Error }
public class MyResultModel
{
public MyResultModel( MyResultType type, string message ) {
switch ( type ) {
case MyResultType.Info: Title = "OK"; break;
case MyResultType.Error: Title = "Error!!!"; break;
}
Message = message;
}
public String Title { get; set; }
public String Message { get; set; }
}
2) Create a Partial View named MyResult in the Shared Folder to handle the model
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyResultModel>" %>
<div id="resultTitle"><%: Model.Title %></div>
<div id="resultMessage"><%: Model.Message %></div>
3) Create and use a BaseController for your controllers and add the following method to it. The method simply add a custom Http Header to the response
protected PartialViewResult PartialView( string viewName, object model, string resultHeader ) {
Response.AppendHeader( "MyHttpCustomHeader", resultHeader );
return base.PartialView( viewName, model );
}
4) In your action return a MyResultView when you've done
[HttpPost]
public virtual ActionResult DoSomething() {
try {
//Do Something
return PartialView( "MyResult",
new MyResultModel( MyResultType.Info, "Operation Completed" ),
"HttpResultInfo" );
}
catch ( Exception ex ) {
return PartialView( "MyResult",
new MyResultModel( MyResultType.Error, ex.Message ),
"HttpResultError" );
}
}
5) Finally, Submit the form using jquery and handle the results.
$.ajax({
type: "post",
dataType: "html",
url: "your/url/here",
data: $("#myform").serialize(),
success: function (response, status, xml) {
var resultType = xml.getResponseHeader("MyHttpCustomHeader");
if (resultType == null) {
//No message do whatever you need
}
else {
//response contain your HTML partial view here. Choose your
//desidered way to display it
}
}
});
With a scenario like this you dont need to place a control on the master page. You can:
Show the view as it comes from the action without any modification
Use some fancy message display technique as StackOverflow does with the orange sliding message (in this case simply extract the title and the message from the returned html)
Use some fancy jquery plugin as jGrowl to show your message
If you want to check wether it is an Info/Error message simply check the custom header with jQuery in the else branch
var title = $(response).filter("#resultTitle").text();
var message = $(response).filter("#resultMessage").text();
if (resultType == "HttpResultInfo") {
showInfoMessage(title, message);
}
else if (resultType == "HttpResultError") {
showErrorMessage(title, message);
}
Hope it helps!
In a controller, as part of the action, you can set a message like this:
public ActionResult MyAction()
{
// Do some stuff
TempData["message"] = "This is a message.";
return View("MyView");
}
In your master page or in your view:
<%
string text = TempData["Message"] as string;
Response.Write(text);
%>

Resources