how can i do, for example, i create a user in users.cshtml view, that it validates to ActionResult Create(RegisterModel um) and if its all ok, i want to return at users.cshtml but always with one javascript alert or similar, with the value of a variable from the action. Can i do this one?
I have it this in my view..
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Crear Usuario</legend>
<div class="editor-label">
Username:
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
Password:
</div>
<div class="editor-field">
#Html.PasswordFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-label">
Repite Password:
</div>
<div class="editor-field">
#Html.PasswordFor(model => model.ConfirmPassword)
#Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>
</div>
<p>
<input type="submit" value="Crear" />
</p>
</fieldset>
And this in my controller action..
public ActionResult Create(RegisterModel um)
{
if (um.Password == um.ConfirmPassword)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(um.UserName, um.Password, um.Email, um.PasswordAnswer, um.PasswordQuestion, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
var alert = MembershipCreateStatus.Success.ToString();
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
var alert = ErrorCodeToString(createStatus);
}
}
//HERE IS WHERE I WANT TO RETURN TO /ADMIN/USERS BUT WITH AN ALERT WITH CONTAINING THE VALUE OF alert IN A JAVASCRIPT OR SIMILAR ALERT WINDOW
return RedirectToAction("Users", "Admin"); ???????
Can i do it something like this?
You could store the message inside TempData just before redirecting to the Users action:
TempData["message"] = "some message that you want to display";
return RedirectToAction("Users", "Admin");
and then inside the Users.cshtml view (which is returned by the Users action to which you redirected) test for the presence of this message and display an alert:
#if (TempData["message"] != null) {
<script type="text/javascript">
alert(#Html.Raw(Json.Encode(TempData["message"])));
</script>
}
i was trying to show error in same view, instead of trying darin's answer i tried other like this using ViewBag and this to show error in another page by returning Partial View
finally i tried using TempData, to maintain the message during post, here i am showing error using bootstrap
action method:
[HttpPost]
public ActionResult RegDetail(User_table usob, FormCollection col)
{
// some other code here
if (!sqlReader.HasRows)
{
TempData["message"] = "Contains some message";
return RedirectToAction("Registration");
}
return RedirectToAction("Index");
}
my registration view:
#if (TempData["message"] != null)
{
<link href="~/css/boostrap.css" rel="stylesheet" />
<script src="~/js/boostrap.min.js"></script>
<div class="alert alert-danger">
<a class="close" data-dismiss="alert">×</a>
<strong style="width:12px">Error!</strong> Thats wrong code no, try entering correct!
</div>
}
if you need to explore more using Tempdata you can check this where Mr.James explains using bootstrap messages, hope helps someone
Related
Good day,
I am trying to use ajax.beginform in my asp.Net MVC project, to create an alert on success.
The problem is that I could not make it work, I am not getting any error message neither.
[HttpPost]
public ActionResult Create(Details details)
{
//do something
//add details to db
return View("Create", details);
}
public class Details
{
public string Name { get; set; }
public string Email { get; set; }
}
This is my view
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
#using (Ajax.BeginForm("Create", new AjaxOptions()
{
OnSuccess= "ajaxSuccess"
}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "Please fix the following errors.")
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<p>
<input type="submit" value="Create" />
</p>
}
#section scripts
{#Scripts.Render("~/bundles/jqueryval")
<script>
function ajaxSuccess () { alert('this is ajaxSuccess'); }
$(document).ready(function ()
{
function ajaxSuccess () { alert('this is ajaxSuccess'); }
});
</script>
}
As you can see, I am using Jquery.unobstrusive-ajax.min.js script. My action is completed and returns to the view, but there is no error in my console, neither an alert. Am I missing something?
Update: I added an alert to the document ready, but did not trigger
**Update 2: ** changed function to function ajaxSuccess () { alert('this is ajaxSuccess'); }
First, look in the Networks tab to see if the script is resolving correctly, or if a 404 is being returned.
Also try not using the tilda and local paths to see if it works:
<script src="../Scripts/jquery-1.8.2.min.js"></script>
<script src="../Scripts/jquery.unobtrusive-ajax.min.js"></script>
Or use the tilda with this approach: Using tilde in script tag src attribute
EDIT: You aren't getting the alert on document.ready because of the inner function; change:
$(document).ready(function ()
{
function ajaxSuccess () { alert('this is ajaxSuccess'); }
});
to:
$(document).ready(function () {
alert('this is document ready');
});
And you will likely see the alert.
I have one big doubt. I have "Customer Form". Customer Form contain 22 fields. I have Db for "Customer Form". it Contain"Multiple tables" with "many to many relationship". If I connect my Db with "Vb express 2012" using "Connection Strings" and also created EDMX file.it shows view for each table. so i tried to bring all fields in "Single view" and tried to insert the data into multiple tables. For that I used "Code First Approach" i followed the method same as like which is mentioned in the below link. Its working Fine.
http://www.codeproject.com/Tips/651495/Inserting-Data-into-Multiple-Tables-using-Code-Fir
Now my question is i finished the "insert" process using Code first approach.. Now " how to do UPDATE process using this approach.. Because i did only the insertion process . still i need to do Update , Details, Delete.. How to do that?
Thanks.
add your customers in a foreach lop in a view and pass each ones primary key to the edit and delete methods of the controller as follows:
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.s1)
</td>
<td>
#Html.DisplayFor(modelItem => item.s2)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.id })
</td>
</tr>
}
then in your controller make a GET method to accept the primary key as a parameter from the view as follows:
public ActionResult Edit(int id)
{
Class1 class1 = db.Class1.Find(id);
return View(class1);
}
and then make a Form in your Edit View to POST back the values as:
#using (Html.BeginForm())
{
<div class="form-horizontal">
<h4>Class1</h4>
<hr />
#Html.HiddenFor(model => model.id)
<div class="form-group">
#Html.LabelFor(model => model.s1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.s1, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.s2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.s2, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
then in your controller make a POST method to accept the model as a parameter from the view as follows:
[HttpPost]
public ActionResult Edit([Bind(Include = "id,s1,s2")] Class1 class1)
{
db.Entry(class1).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
Similarly make GET and POST methods for Delete.
basically in an update method...
Find the object to be updated
-Example your datacontext class object=ctx,tablename=details
update the found object with the new data
if you're not passing an entire object to the method then just pass the primary key of the object to be updated and the new values
public void update(details newData)
{
var result=ctx.details.Find(id);
result.name=newData.Name;
result.age=newData.Age;
ctx.SaveChanges();
}
to Delete:
a similar process
Find the object -Example your datacontext class object=ctx,tablename=details
Remove it
public void Delete(int id)
{
var result=ctx.details.Find(id);
ctx.details.Remove(result);
ctx.SaveChanges();
}
I am trying to generate an email for forgot password in my project. But when ever i click the send password button it gives me an error:- Uncaught TypeError: Cannot read property 'handler' of undefined. Below is my code.
I am Using the html classes created by webflow in my view and also the webflow. JS script. I am getting the error:-Uncaught TypeError: Cannot read property 'handler' of undefined in the below code of webflow.js. I want that when i click i should get the mail on my email id. I am using sendgrid for sending the email.
my Js code:-
function addListeners() {
listening = true;
// Handle form submission for Webflow forms
$doc.on('submit', namespace + ' form', function(evt) {
var data = $.data(this, namespace);
if (data.handler) {
data.evt = evt;
data.handler(data);
}
});
}
My View code:-
#model InCubatize.Models.User
#{
ViewBag.Title = #Resources.LanguageResource.ForgotPasswordTitle;
}
<div class="w-container logo_container"><img class="login_logo" src="~/Images/images/Logo%20-%20Blue%20(V).png" width="100" alt="5488354fba4bc2be7fd98967_Logo%20-%20Blue%20(V).png">
</div>
<div class="w-container login_form_container">
<div class="w-form">
#using (Html.BeginForm()) {
<div class="card_main login_card_nest" id="email-form" name="email-form" data-name="Email Form" data-redirect="/login">
#Html.TextBoxFor(model => model.Email, new { #class="w-input login_textfield", id="Reg-Email", type="email", placeholder="Email", name="Reg-Email", data_name="Reg Email", required="required" })
<br />
#Html.ValidationMessageFor(model => model.Email)
<input class="w-button login_button" type="submit" value="Recover my password" data-wait="Please wait...">
#Html.ValidationSummary(true, "", new { #class= "ValidationSummaryMessages" })
<div class="login_textblock">New user?
Create account
<span class="back_to_login">
Back to login</span>
</div>
</div>}
<div class="w-form-done">
<p>Thank you! Your submission has been received!</p>
</div>
<div class="w-form-fail">
<p>Oops! Something went wrong while submitting the form :(</p>
</div>
</div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="~/Scripts/js/webflow.js"></script>
my HTTP Post method:-
[HttpPost]
public ActionResult ForgotPassword(string email)
{
try
{
User lUser = new User();
var userQuery = from u1 in db.Users
where u1.Email == email
select u1;
List<User> userList = userQuery.ToList();
if (userList.Count > 0)
{
foreach (User cu in userList)
{
if (cu.Status == (int)Enums.UserStatusType.Active)
{
string msg = HttpContext.GetGlobalResourceObject("LanguageResource", "ForgotYourPasswordEmailBody").ToString();
msg = msg.Replace("[FULLNAME]", cu.FullName);
string decryptedPassword = Encrypt.DecryptString(cu.Password);
decryptedPassword = decryptedPassword.Remove(0, cu.Id.ToString().Length);
msg = msg.Replace("[PASSWORD]", decryptedPassword);
string emailFrom = Helpers.CommonFunctions.GetApplicationSettingValue("SystemEmailId");
Emailer.SendEmail(cu.Email, HttpContext.GetGlobalResourceObject("LanguageResource", "ForgotYourPasswordEmailSubject").ToString(), msg, emailFrom);
ModelState.AddModelError("", HttpContext.GetGlobalResourceObject("LanguageResource", "ForgotYourPasswordEmailSuccessMessage").ToString());
return View();
}
else
{
ModelState.AddModelError("", HttpContext.GetGlobalResourceObject("LanguageResource", "InactiveUserMessage").ToString());
return View();
}
}
}
return View();
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.ToString());
return View();
}
}
I have a textbox on my MVC 4 view, and I would like to let the user press Enter on changing the text and call a controller's action method. Thanks.
Here is a part of my view:
#using (Html.BeginForm())
{
<div class="editor">
#Html.LabelFor(m => m.FolderPath)
#Html.TextBoxFor(m => m.FolderPath, new { #Id = "FolderPath", #style="width:500px;" })
#Html.ValidationMessageFor(m => m.FolderPath)
</div>
And a part of the controller:
[HttpPost]
[MultipleButton(Name = "action", Argument = "Refresh")]
public ActionResult Refresh(EdiFileModel ediFileModel)
{
if (Directory.Exists(ediFileModel.FolderPath))
{
FolderPath = ediFileModel.FolderPath;
}
else
{
ModelState.AddModelError("FolderPath", "This folder does not exist!");
}
ediFileModel = Load();
return View("Index", ediFileModel);
}
Add a submit button...
<input type="submit" value="Submit"/>
inside your form.
I have a view with two partials in it that use ajax to post their forms to actions. The onsuccess callback redirects the user to another url. However I don't want this onsuccess function to be called when the modelstate is not valid. I've tried returning a 400 level error from my controller to trigger the onfailure function but it causes some weird behavior and the validation errors don't display. Here's my code
Action:
[AllowAnonymous]
[DisableCache]
public ActionResult Login(string returnUrl ="/") //This is the view that contains the two other partial views.
{
var path = VirtualPathUtility.ToAbsolute(returnUrl);
var url = new Uri(Request.Url, path).AbsoluteUri;
ViewBag.ReturnUrl = url;
return View();
}
[AllowAnonymous]
public ActionResult _LoginPartial()
{
return PartialView(new LoginModel());
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult _LoginPartial(LoginModel model)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return PartialView();
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
Response.StatusCode = 400;
return PartialView(model);
}
Login View:
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
</hgroup>
#section CustomScripts {
#if (ViewData.ModelState.IsValid){
<script type ="text/javascript">
function OnSuccess() {
var returnUrl = #Html.Raw(Json.Encode(ViewBag.ReturnUrl))
window.location = returnUrl;
}
function OnFailure() {
alert("Fail");
}
</script>
}
}
<section id="loginForm">
#{
if(!WebSecurity.IsAuthenticated){
<h2>Use a Creative Works account to log in.</h2>
#Html.Action("_LoginPartial")
#Html.ActionLink("Forgot your password?", "ResetPassword")
}
}
</section>
<section id ="RegisterForm">
#{
if(!WebSecurity.IsAuthenticated){
<span>Don't have an account? Make one!</span>
#Html.Action("RegisterPartial", new { returnUrl = ViewBag.ReturnUrl })
}
}
</section>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
_LoginPartial view
#model Cwo.Domain.Entities.LoginModel
#{
ViewBag.Title = "LoginPartial";
}
#using (Ajax.BeginForm("_LoginPartial",
new AjaxOptions(){UpdateTargetId = "loginForm",
InsertionMode = InsertionMode.Replace, OnSuccess = "OnSuccess", OnFailure = "OnFailure"
})) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Log in Form</legend>
<ol>
<li>
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</li>
<li>
#Html.LabelFor(m => m.Password)
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</li>
<li>
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe, new { #class = "checkbox" })
</li>
</ol>
<input type="submit" value="Log in" />
</fieldset>
}
The formatting got kinda messed up pasting in here, sorry about that. Instead of an alert("fail") response I want the validation errors to display. If there's a better way than returning a 400 level error from the action please teach me!
I think another way to word you problem is you don't want the contents of the onsuccess function to be executed? if this is the case then move your #if (ViewData.ModelState.IsValid){ ... } to inside the OnSuccess function. if state is invalid that function would have no guts so nothing gets done.
personally I like keeping javascript separate from razor...even more, the javascript should reside in its own js file. in this case you could use razor to set a bool javascript variable to a function or object constructor, which would then do your success work only if variable was true.