I have this code:
#if (!string.IsNullOrWhiteSpace(Model.ErrorMessage))
{
<script>
$('#modalError').modal('show');
</script>
Response.Write("<script>alert('hello');</script>");
HttpContext.Current.Response.Write("<script>alert('hello');</script>");
}
Where check if Model.Error Message is different from empty, so I an alert to the user, but none of the forms submitted by the condition if this working, how can it be done?
already I tried so:
#if (!String.IsNullOrEmpty(ViewData["erro"] as string))
{
<script>alert(#ViewData["erro"]);</script>
}
This and a part of the view.
My controller this way:
public ActionResult Login(LoginViewModel model, SignInMessage message)
{
if (!String.IsNullOrEmpty(model.ErrorMessage))
ViewData["erro"] = !String.IsNullOrEmpty(model.ErrorMessage) ? model.ErrorMessage : null;
return this.View(model);
}
I want to display a javascript message because I will use the modal Bootstrap
#Alexandre Lima,
As pointed out in comments by others and I agree too, not sure if your approach is right or if it is then we need more information, that said, You have the following options
Use simple data validations on your view models to notify users of
an invalid email - this is built into MVC for you - MVC's data
annotation. Here are links
http://www.asp.net/mvc/overview/older-versions-1/models-data/performing-simple-validation-cs
From your comment, looks like you want to display something on login
failures , meaning your server code got back saying Auth failed,
if that is the case, am assuming here you have something like this
on your controller code
public ActionResult Login(LoginModel login)
{
if(ModelState.IsValid)
{
//you call your service to get back the result
if(!NotAValidUser)
{
ModelState.AddModelError("LoginFailed", "The user name and or password is incorrect.")
}
}
}
in your View
#Html.ValidationMessage("LoginFailed") // this will display the above message
If it's a View, then you might be better off using Javascript/JQuery. To do that, you'll need to add a hidden field somewhere in your HTML and set the value to Model.ErrorMessage. Like this:
<input type="hidden" id="hdError" value="#Model.ErrorMessage" />
Then at the end of your HTML body, you add the Javascript code:
<script>
$(function() {
var errorStr = $("#hdError").val();
if (errorStr) {
alert("hello"); //or any other alert message
}
});
</script>
Related
I have a form with some input fields and when you click on Save, I do a check if a field already exist in the database. I have a service method for this.
For example in the database the field with value "Test10" already exist and if the user use "Test10" in the input field and clicks on save I want to show this message :
private async Task<bool> CheckIfCodeAlreadyExist(string code)
{
return await _service.CheckCodeExist(code);
}
I tried with session vaiables, with an extra bool parameter but not effective enough.
My JavaScript knowlegde is not that much, but would it possible to check this with a "onClick" event in the form?
If the result is true you stay on the page with the message.
Don't mind the Model.Code is red.
Take a look at Microsoft's documentation for model validation, specifically remote validation. The use case and example for this is almost identical to yours:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.2#remote-attribute-1
The [Remote] attribute implements client-side validation that requires
calling a method on the server to determine whether field input is
valid. For example, the app may need to verify whether a user name is
already in use.
In your case, you may use a model with a Code property like this one:
[Remote(action: "CheckCode", controller: "Home")]
public string Code { get; set; }
On the server under the corresponding controller, you can provide the endpoint needed to validate the code:
[AcceptVerbs("Get", "Post")]
public IActionResult CheckCode(string code)
{
if (!yourService.VerifyCode(code))
{
return Json($"Code {code} is already in use.");
}
return Json(true);
}
You don't need to do it with onClick if you have liberty to use Remote validation .net MVC offers.
Decorate you model property with something like:
[Remote("Action", "Controller", ErrorMessage = "Invalid Code")]
Or pass additional fields as well:
[Remote("Action", "Controller", AdditionalFields = "Id", ErrorMessage = "Invalid Code")]
with javascript and jquery, you do ajax request.
Bind click event to button:
$('#button').on('click', function(){
$.ajax({
url: '/Controller/Action',
method: 'get',
data: {
code: $('#Code').val()
}
}).done(function (result) {
if (result) {
// code valid
$('form').submit();
} else {
// show error
}
}).fail(function () {
// ajax request failed
});
});
Controller/Action to return bool:
public async Task<bool> CheckIfCodeAlreadyExist(string code)
{
return await _service.CheckCodeExist(code);
}
I know that this question was answered many times, but since I don't know much about javascript, and this is my first website, I followed the answer in this link. This is my code so far:
<li>#Html.ActionLink("Save","SaveClass",new { path2=Model.path,code="xxx"},new { id="save"})</li>
#Html.TextAreaFor(m=>m.code, new { id = "code" })
<script>
$("#save").click(function(evt) {
var fakedUri = $("#save").attr("href");
alert($('#code').val());
var uri = $("#save").attr("href").replace("xxx", $("#code").val());
});
</script>
And this is my controller:
public ActionResult SaveClass(string path2,string code)
{
modelSC.path = path2;
modelSC.code = code;
System.IO.File.WriteAllText(Server.MapPath(modelSC.path), code);
return RedirectToAction("Index");
}
The code always saves 'xxx' to the file, and throws:
The requested content appears to be script and will not be served by
the static file handler.
How can I get it to work?
ActionLink helper generates a link and clicking on that will issue a GET request. Looks like you are trying to send the value of the text area through querystring to the next action method. But GET might not be the best solution to handle that. Querystring has a limit on how much data it can handle (varies for different browsers).
Ideally you should do a form submit, If you do not prefer a button, but want a link to initiate the form submit, that is possible with a little javascript.
#using(Html.BeginForm("SaveClass","YourControllerName"))
{
#Html.TextAreaFor(m=>m.code)
#Html.HiddenFor(s=>s.path)
#Html.ActionLink("Save","SaveClass","YourControllerName",null,new { id="save"})
}
Now in your javascript, when click on the link, stop the default behavior (the default GET Action) and then submit the form where the clicked link is present. We can use the closest() method.
$(function(){
$("#save").click(function(e){
e.preventDefault();
$(this).closest("form").submit();
});
})
Make sure you use the correct parameter name (matching with the input name)
public ActionResult SaveClass(string path,string code)
{
// to do : return something
}
I am using AJAX controller to provide the object from the server side. User enters the input, and AJAX controller provides the object for that input request. I have a complex validation logic so I have written it in Java, and put it in the AJAX controller. It looks like this:
#RequestMapping(value = "api/user/{user}", produces = "application/json", method = RequestMethod.GET)
public #ResponseBody UserData execute(#PathVariable(value = "user") String user) {
if(validator.isValid(user)) {
return service.getUserData(user);
} else {
throw new ResourceNotFoundException(INVALID_USER_FORMAT);
}
In Javascript, I call the AJAX controller like this:
// obtain user from text input
var user = $('#user_input').val();
$.getJSON("/api/user/"+user, function (data) {
// ...
});
Now, I want to display on the UI an error message where the entered user in '#user_input' is invalid. And I want to use the validation logic from my controller, and not to have duplicated validation logic also in Javascript.
What should I return from my AJAX controller when the validation doesn't succeed, and how to make use of that in Javascript, so that I can display something like "User format invalid"? What is the best practice?
I got "MultiLanguageProvider" which is ordinary C# class, not Controller or Model. The idea is when user clicks Change language - it must call back server-side void ChangedLanguage() on MultiLanguageProvider instance. This doesn't work at all:
#MultiLanguageProvider.Instance.SelectAppropriate("на русском", "in english")
- 'cause all the code inside #{ } get executed immideately - at the time of page-load. I am not informed about AJAX, so maybe someone of u can show me the right direction to do this simply job?
I don't understand which one you are trying to invoke on anchor tag click. But if I understand the essence of your question, you are trying to call some server side method to change the language, and here I assume you want to save the language selection that was made on user interface (UI). If this is what you are looking, on client side, you do the changes suggested by Stephen Muecke. On server side, you need to add a [HTTPPOST] action method on controller something like:
public ActionResult SwapLanguage(LanguageViewModel languageViewModel)
{
//do the save action => like saving to database
return Json(new { data = {urlToRedirt: "/someUrl_GeneratedVia_UrlHelper"},
status = "success",
message = "Language Changed Successfully" }, JsonRequestBehavior.AllowGet);
}
}
On Client side:
$('#swaplanguage).on('click', function(event) {
event.preventDefault();
$.post( '#Url.Action("SwapLanguage")', function( data ) {
// Handle the server side response here.
// Like if you want to redirect, use something like:
// window.location = data.urlToRedirt;
});
}
Of course, you need to handle error conditions on both client as well as server side.
If you don't want to save anything, and you just want to redirect user to some url based on the language user selects, then your onclick event handler is something like:
$('#swaplanguage).on('click', function(event) {
urlToRedirect = 'url_to_redirect' + '/' + $('#languageDropDownId').val();
window.location = urlToRedirect;
}
Finally, your anchor tag is:
<a id="swaplanguage">Change Language</a>
Hope that helps.
I'm using ASP.NET MVC4 to create an application and I'm facing an issue regarding AJAX and partial views.
Right now, I have a view rendering :
a partial view (called _createUser) which is a modalbox containing a Form to create a user in my application (rendered via #{Html.RenderPartial("_createUser");})
a partial action (called ListUsers) which is an action that simply renders users currently registered in my application (rendered via #{Html.RenderAction("users");} in an html table
When the user clicks a button, the modal box contained in _createUser is displayed via jquery so the user can type informations about a new user. When he clicks on a button in the modal box, the form is submitted via AJAX to an action in my controller which checks ModelState.IsValid.
And this is where I'm stuck because I don't know what is the correct way of handling success/error with partial view using jquery because if the model is correct and the registration is correct, I want to refresh only the list of users.
Is the model is not valid, I want to refresh the modal box with errors raised by the ModelState.
My action is :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register( RegisterModel model )
{
if( ModelState.IsValid )
{
try
{
WebSecurity.CreateUserAndAccount( model.UserName, model.Password );
WebSecurity.Login( model.UserName, model.Password );
ViewBag.CreateUserSucceded = true;
return RedirectToAction( "ListUsers" );
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError( "", ErrorCodeToString( e.StatusCode ) );
}
}
return PartialView( "_createUser", model );
}
My jquery is pretty simple too :
function SubmitCreateUserForm() {
$.ajax({
type: "POST",
url: '#Url.Action("Register")',
data: $("#createUserForm").serialize(),
success: function (result, status, jqXHR) {
????
}
});
}
I think the correct way should be to use JSON and, instead of returning and ActionResult, I should return some JSON containing for a status field and the data related to my users list or validation errors and using the status field to know which part of my main view must be updated.
By I really don't know how to mix JSON result and a razor view. Any clue?
Updated (I can't answer my own question right now or I have to wait 8 hours).
Ok, I ended up using what I found in this link http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/
It's pretty straightforward and does the job really well!