Return Succes Message After Delete/Update/create - ajax

This is my GesAgence Page action :
public ActionResult GesAgence()
{
var test = new Models.J2VEntities();
return View(test.agence);
}
This is my Action for Deleting :
public ActionResult DeleteAg(string id)
{
Models.J2VEntities entity = new Models.J2VEntities();
Models.agence model = (from p in entity.agence
where p.Idag == id
select p).SingleOrDefault();
//Sauvgarde ds la BD
entity.agence.DeleteObject(model);
entity.SaveChanges();
return View("gesAgence");
}
So i'm wondring how to return Succes message after deleting(i tried with TempData but didn't succed because my gesAgence must return model not TempData).

You can use Ajax to call your controller from your viewpage and pop up the message whatever your controller returned, try something like this.
Script on your view page.
function onDeleteAg (id) {
var answer = confirm("Are you sure you want to delete AG ?")
if (answer) {
$.ajax(
{
type: "Get",
url: '<%= Url.Action("DeleteAg","YourControllerName") %>',
data: { agId: id },
success: function (data) {
//HERE--data is the message you that your controller DeleteAg method will return after it's called. you need to do something here to display this message(data) anywhere you want to . something like below.
alert(data);
},
error: (function () { alert("Error! Ag was not deleted." ); })
});
}
};
Method on your controller.
public string DeleteAg(string agId)
{
try{
Models.J2VEntities entity = new Models.J2VEntities();
Models.agence model = (from p in entity.agence
where p.Idag == id
select p).SingleOrDefault();
//Sauvgarde ds la BD
entity.agence.DeleteObject(model);
entity.SaveChanges();
}
catch(Exception ex)
{
return "AG has not been deleted successfully;
}
return "AG has been deleted successfully;
}

you can call this method via ajax and return JsonResult instead of ActionResult, by looking result you can show message to user.
public JsonResult DeleteAg(string id)
{
Models.J2VEntities entity = new Models.J2VEntities();
Models.agence model = (from p in entity.agence
where p.Idag == id
select p).SingleOrDefault();
//Sauvgarde ds la BD
entity.agence.DeleteObject(model);
entity.SaveChanges();
var json = new
{
success = true
};
return Json(json);
}

You can set Success to ViewBag
public ActionResult DeleteAg(string id)
{
Models.J2VEntities entity = new Models.J2VEntities();
Models.agence model = (from p in entity.agence
where p.Idag == id
select p).SingleOrDefault();
//Sauvgarde ds la BD
entity.agence.DeleteObject(model);
entity.SaveChanges();
ViewData["Success"] = true;
return View("gesAgence");
}
in view
#if(ViewData["Success"] != null && (bool)ViewData["Success"]){
<script>alert("Sucess!");</script>
}
This is my view :
<% if(ViewData != null && ViewData["Success"] != null && (bool)ViewData["Success"]){ %>
<script type="text/javascript"> alert("Sucess!");</script>
<% } %>
<div class="clear">
</div>
<div id="main">
<h1> Demande preinscrit</h1>
<ul class="listing">
<% foreach (var item in Model) { %>
<li>
<div class="listinfo">
<h3>
<%: Html.DisplayFor(modelItem => item.Nomag) %>
</h3>
<p>
<%: Html.DisplayFor(modelItem => item.Idag) %>
</p>
<span class="price"> <%: Html.DisplayFor(modelItem => item.Adrag) %> <%: Html.DisplayFor(modelItem => item.Vilag) %> <%: Html.DisplayFor(modelItem => item.Gov) %></span> <span class="media">Tel : <%: Html.DisplayFor(modelItem => item.Telag) %> |</span> <%: Html.DisplayFor(modelItem => item.Mailag) %>
</div>
<div class="listingbtns">
<span class="listbuttons"><%: Html.ActionLink("Bloque", "Bloque", new {id= item.Idag}) %> </span>
<span class="listbuttons"><%: Html.ActionLink("Supprime", "DeleteAg", new { id = item.Idag })%></span>
</div>
<div class="clear">
</div>
</li>
<% } %>
i got this error : System.NullReferenceException: Object reference not set to an instance of an object on this line <% foreach (var item in Model) { %>.

Related

Ajax Results Div Hidden Until Result

I have an Ajax form which is working properly:
<div class="row">
<div class="col-sm-8 col-sm-offset-2 alert alert-info" id="result"></div>
<div class="col-sm-8 col-sm-offset-2">
<h4>Contact Us</h4>
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
{
#Html.LabelFor(a=>a.Email)
#Html.EditorFor(a => a.Email)
#Html.ValidationMessageFor(a => a.Email)
#Html.LabelFor(a=>a.Name)
#Html.EditorFor(a => a.Name)
#Html.ValidationMessageFor(a => a.Name)
#Html.LabelFor(a=>a.Phone)
#Html.EditorFor(a => a.Phone)
#Html.ValidationMessageFor(a => a.Phone)
#Html.LabelFor(a=>a.Message)
#Html.EditorFor(a => a.Message)
#Html.ValidationMessageFor(a => a.Message)
<input type="submit" class="btn btn-primary" value="Send Message" />
}
</div>
However, the results div, which I'd like to be styled as an alert, is always displaying by default. How can I make it display only when it has inner text? Is there something like #if(AjaxResult != null) { <div>...</div> }?
I suspect this can be solved within the View only, but I'm including my Controller code below for completeness:
[HttpPost]
public ActionResult Index(ContactUsViewModel model)
{
var fromAddress = new MailAddress("X", "X");
var toAddress = new MailAddress("X", "X");
string fromPassword = "X";
string subject = "GN Query";
string body = model.Message;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
return Content("Your message has been received and we will respond within 24-48 hours.", "text/html");
}
You can create a partial view call _alert with your html:
<div class="col-sm-8 col-sm-offset-2 alert alert-info" id="result">
Your message has been received and we will respond within 24-48 hours.
</div>
and then in your view you can set a container div in which it will be rendered when ajax call completes:
<div id="messageContainer">
</div>
now your action should return that partial view and you can have a boolean in your view to decide either render or not:
#model System.Boolean
#if(Model)
{
<div class="col-sm-8 col-sm-offset-2 alert alert-info" id="result">
Your message has been received and we will respond within 24-48 hours.
</div>
}
your controller action will decide either the operation was successful and show the message or not:
bool isSuccess = true; // your logic to set this flag
............
............
{
smtp.Send(message);
}
return PartialView("_alert.cshtml",isSuccess );
and in main view you will have :
<div id="messageContainer">
</div>
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "messageContainer" }))
Hope it helps.

What to put in Inherits part in Partial in mvc3

i have in my controller and im not sure if i have it correct
[HttpGet]
[NoCache]
public ActionResult ListCommentsOnNews(int newsId, string newsComment) ???
{
//code here with return
}
in my Article.aspx view:
<div class="news-comment-content" id="news-comment-content">
<% if (Model.Results != null)
{ %>
<% foreach (var newsItem in Model.Results.NewsComments)
{ %>
<% Html.RenderPartial("SetCommentOnNews", newsItem); %>
<%} } %>
</div>
then my partial ListCommentsOnNews.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<???>" %>
<div class="news-post-list-item">
<div class="news-post-user-info-wrapper">
<div class="avatar">
<img width="52" height="52" alt="Avatar" src="/ThemeFiles/Base/images/User/user-avatar.png" />
</div>
<div class="who-and-when-box">
<%: newsItem.CommentDate %> //get error here
<br />
<br />
<%: ViewBag.UserName %>
</div>
<div class="news-comment"><%: newsItem.NewsComment %></div> //and get error here
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
my controller:
[HttpGet]
public ActionResult Article(int id, int? page)
{
var news = ZincService.NewsService.GetNewsForId(id);
var allNewsComments = ZincService.NewsService.GetAllNewsCommentsForId(id, page.GetValueOrDefault(1), 10);
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
if (news == null || news.PublishingState != PublishingState.Live)
return RedirectToAction("NotFound");
if (allNewsComments != null)
{
var user = ZincService.GetUserForId(currentUser.UserId);
if (user == null || user.Customer.CustomerId != CurrentCustomer.CustomerId)
return DataNotFound();
ViewBag.Avatar = user.UserImage;
ViewBag.UserName = user.Firstname + " " + user.Surname;
NewsCommentsViewModel model = (NewsCommentsViewModel)SetNewsArticleViewModel(news, new NewsCommentsViewModel());
foreach (var newsItem in allNewsComments.NewsComments)
{
model.Results = allNewsComments;
model.PageSize = 10;
model.CurrentPage = page.GetValueOrDefault(1);
}
return View(model);
}
else
{
return View(SetNewsArticleViewModel(news,null));
}
}
[NonAction]
private NewsArticleViewModel SetNewsArticleViewModel(Entities.News.News news, NewsArticleViewModel viewModel)
{
viewModel.News = news;
viewModel.IsFavourite = ZincService.FavouriteService.IsFavouriteForUser(CurrentUser.UserId, news);
viewModel.DownloadAttachments = news.NewsAttachments.Where(x =>
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.Excel ||
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.PDF ||
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.PowerPoint ||
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.Word);
viewModel.EmbedAttachments = news.NewsAttachments.Where(x =>
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.Video);
return viewModel;
}
i get errors on the newsItem parts stating that it does not exist in the current context.
can some one help me right please?
As i inferred from code you posted, problem is with you'r usage of Model.you are trying to use model properties,but you are not doing it correctly.try following :
<%
Model.CommentDate
%>
instead of
<%: newsItem.CommentDate %> //get error here

How to make use of Viewbag in my View

I dont understand, I have my in my Controller:
[HttpGet]
public ActionResult Detail(int userId)
{
var user = ZincService.GetUserForId(userId);
if (user != null)
{
ViewBag.user = userId;
ViewBag.email = user.Email;
ViewBag.title = user.JobTitle;
ViewBag.node = user.Node;
}
return View(user);
}
then my view, Detail.aspx
<div id="user-details-view">
<div>
Title:
</div>
<div>
<%: Model.JobTitle %>
<%: Model.News %>
<%: Model.Node %>
</div>
<div>
<%: Html.ActionLink("Change Email Address", "ChangeEmailAddress", new { #id = Model.UserId })%>
</div>
</div>
when I run my app i get an error:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Areas/Admin/Views/User/Detail.aspx
I dont understand? Is it because of syntax errors?
Previous posts are correct as in logic but you assigned the viewbag names in your controller differently. It should be:
<div id="user-details-view">
<div>
Title:
</div>
<div>
<%: ViewBag.email %>
<%: ViewBag.title %>
<%: ViewBag.node %>
</div>
<div>
<%: Html.ActionLink("Change Email Address", "ChangeEmailAddress", new { #id = ViewBag.user })%>
</div>
</div>
Hope it helps..
It must be like this
<%: ViewBag.JobTitle %>
<%: ViewBag.News %>
<%: ViewBag.Node %>
Replace the Model. with ViewBag.
<%: ViewBag.title %>
<%: ViewBag.email %>
<%: ViewBag.node %>
and also change this
<%: Html.ActionLink("Change Email Address", "ChangeEmailAddress", new { id = ViewBag.user })%>
You must use that sintax:
<%: ViewBag.email %>
<%: ViewBag.title %>
<%: ViewBag.node %>
But would be better if you use Model:
public class UserInfo
{
public int UserId { get; set; }
public string Email { get; set; }
public string Title { get; set; }
public NodeType Node { get; set; }
}
[HttpGet]
public ActionResult Detail( int userId )
{
var data = ZincService.GetUserForId( userId );
var user = new UserInfo();
if ( data != null )
{
user.UserId = userId;
user.Email = data.Email;
user.Title = data.JobTitle;
user.Node = data.Node;
}
return View( user );
}
In view (MVC3) with razor sintax:
#model UserInfo
<div id="user-details-view">
<div>
Title:
</div>
<div>
#Model.Title
#Model.Node
</div>
<div>
#Html.ActionLink("Change Email Address", "ChangeEmailAddress", new { #id = Model.UserId })
</div>
</div>

Create button click function not working in mvc3?

Hi guys i have a table where i have a add new project link ...when i click on that it takes me to a create page where i have textboxes for inserting new record and a button to create..but i click on create button its not working can any one help me where am i doing wrong here is my code
This is my create.aspx page:
<%: ViewBag.Title="Create" %>
<fieldset>
<legend>Projects</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.projectName)%>
</div>
<div class="editor-field">
<%:Html.EditorFor(model => model.projectName)%>
<%: Html.ValidationMessageFor(model => model.projectName)%>
</div>
<div class="editor-label">
<%:Html.LabelFor(model => model.Description)%>
</div>
<div class="editor-field">
<%:Html.EditorFor(model => model.Description)%>
<%:Html.ValidationMessageFor(model => model.Description)%>
</div>
<div class="editor-label">
<%:Html.LabelFor(model=>model.status) %>
</div>
<div class="editor-field">
<%:Html.EditorFor(model=>model.status) %>
<%:Html.ValidationMessageFor(model=>model.status) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
And this is my controller function:
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(ProjectModel model)
{
var modelList = new List<ProjectModel>();
using (SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True"))
{
conn.Open();
SqlCommand insertcommande = new SqlCommand("Sp_AddNewProject", conn);
insertcommande.CommandType = CommandType.StoredProcedure;
insertcommande.Parameters.Add("#ProjectName", SqlDbType.VarChar).Value = model.projectName;
insertcommande.Parameters.Add("#Description", SqlDbType.VarChar).Value = model.Description;
insertcommande.Parameters.Add("#Status", SqlDbType.VarChar).Value = model.status;
insertcommande.ExecuteNonQuery();
}
return View( modelList);
}
when i click on create button in aspx page it should go to create method in my controller .....what am i doing wrong here.........
I put this in my create.aspx page BeginForm statement:
<% using (Html.BeginForm()) { %>
<form action=”/members/Create” method=”post”></form>
and added
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.post)]
public ActionResult Create(ProjectModel model)
{
var modelList = new List<ProjectModel>();
using (SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True"))
{
conn.Open();
SqlCommand insertcommande = new SqlCommand("Sp_AddNewProject", conn);
insertcommande.CommandType = CommandType.StoredProcedure;
insertcommande.Parameters.Add("#ProjectName", SqlDbType.VarChar).Value = model.projectName;
insertcommande.Parameters.Add("#Description", SqlDbType.VarChar).Value = model.Description;
insertcommande.Parameters.Add("#Status", SqlDbType.VarChar).Value = model.status;
insertcommande.ExecuteNonQuery();
}
return View( modelList);
}
There is no form in your View. That is one problem.
Visit MSDN for BeginForm: http://msdn.microsoft.com/en-us/library/dd410596.aspx

ModelState.IsValid returns false when it should be true

I have a pretty simple MVC 2 form. It has two dropdowns, user and role. The employee dropdown passes validation, and the role dropdown does not, regardless of what I select. There is no default "empty" option although I plan to implement one, which is why I need the validation to work. It fails both client and server validation. I just can't see why one would work and one does not!
The Form:
<% using (Html.BeginForm()) {%>
<%:Html.ValidationSummary(true) %>
<%:Html.EditorFor(model => model.User, new { AllEmployees = Model.AllEmployees, RoleList = Model.RoleList })%>
<p>
<input type="submit" value="Add New User" />
</p>
<% } %>
<% Html.EndForm(); %>
The Editor Template:
<tr>
<td>
<div class="editor-label">
<%: Html.LabelFor(model => model.UserId) %>
<%: Html.RequiredMarkFor(model => model.UserId) %>
</div>
</td>
<td>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.UserId, new SelectList(ViewData["AllEmployees"] as IEnumerable, "UserId", "DisplayName", Model.UserId)) %>
<%: Html.ValidationMessageFor(model => model.UserId>
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-label">
<%: Html.LabelFor(model => model.AccessLevel)%>
<%: Html.RequiredMarkFor(model => model.AccessLevel)%>
</div>
</td>
<td>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.AccessLevel, new SelectList(ViewData["RoleList"] as IEnumerable, Model.AccessLevel))%>
<%: Html.ValidationMessageFor(model => model.AccessLevel)%>
</div>
</td>
</tr>
The Metadata:
[DisplayName("Employee")]
[Required(ErrorMessage = "Please select an employee.")]
[StringLength(8, ErrorMessage = "User Id must be less than 8 characters.")]
[DisplayFormat(ConvertEmptyStringToNull = false,
HtmlEncode = true)]
[DataType(DataType.Text)]
public object UserId { get; set; }
// Validation rules for Access Level
[DisplayName("Role")]
[Required(ErrorMessage = "Please select the role for this user.")]
[StringLength(15, ErrorMessage = "Role must be under 15 characters.")]
[DisplayFormat(ConvertEmptyStringToNull = false,
HtmlEncode = true)]
[DataType(DataType.Text)]
public object AccessLevel { get; set; }
The Get Action:
List<String> roles = (from o in txDB.Users
select o.AccessLevel).Distinct().ToList();
var viewModel = new UserViewModel
{
User = new User(),
AllEmployees = empList,
RoleList = roles
};
return View(viewModel);
The Post Action:
[HttpPost]
[AuthorizeAttribute(Roles="Administrator")]
public ActionResult Create(User user)
{
if(!ModelState.IsValid)
{
//ModelState is invalid
return View(new User());
}
try
{
//do stuff
}
}
The Required Helper Method (from Define markup for [Required] fields in View in ASP.NET MVC 2.0):
public static string RequiredMarkFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
if(ModelMetadata.FromLambdaExpression(expression, helper.ViewData).IsRequired)
return "*";
else
return string.Empty;
}
Post method should be as follows to get Server side validation...
[HttpPost]
[AuthorizeAttribute(Roles="Administrator")]
public ActionResult Create(User user)
{
if(!TryUpdateModel(user))
{
// Model is INVALID
return View(user);
}
else
{
// ModelState is VALID
// Do stuff
}
}
The else might be redundant depending on what you're doing but that should get you going.
In the view above your <% using Html.BeginForm() %> you need
<% Html.EnableClientValidation(); %>
You also need to reference the scripts, MicrosoftAjax and MicrosoftMvcValidation I think
First of all: You have two closing form tags
If you use
<% using (Html.BeginForm()) {%>
<% } %>
you dont need to use this
<% Html.EndForm(); %>
Regarding your validation problem you are using an editor only for your User property, which is the only one that get binded by the model binder
<%:Html.EditorFor(model => model.User, new { AllEmployees = Model.AllEmployees, RoleList = Model.RoleList })%>
Try to replace the previous code with an EditorForModel as your Editor Template is for a model class.
So your form should change in
<% using (Html.BeginForm()) {%>
<%:Html.ValidationSummary(true) %>
<table>
<%:Html.EditorForModel()%>
</table>
<p>
<input type="submit" value="Add New User" />
</p>
<% } %>
and you're done!

Resources