I have a simple mvc application which perform the CRUD functionality to manage UserDetials. I need to show a confirmation box when trying to delete a record.
You could attach a submit handler with javascript to the form that is performing the deletion. Here's an example with jquery:
Assuming the following delete form:
<%: Html.BeginForm("Destroy", "Product", FormMethod.Post,
new { id = "deleteForm" }) { %>
<%: Html.HttpMethodOverride(HttpVerbs.Delete) %>
<%: Html.HiddenFor(x => x.Id) %>
<input type="submit" value="Delete product" />
<% } %>
You could use jquery to attach a .submit() handler and ask for user confirmation:
$(function() {
$('#deleteForm').submit(function() {
return confirm('Are you sure you want to delete this product');
});
});
Related
I have a "User" model and a "Lab" model.
When I create a new Lab object, I want to be able to pick up users from a list in a "select" html form...
So, in the view of lab/new.ejs I first display all the users in the User model database in the server console by doing:
<% User.find(function(err, users) {
_.each(users, function(user) {%>
<%console.log(user.name)%>
<% })
});%>
And it displays the list of all my users names correctly.
But when I try put all these users in a select form just below, the select form return empty with the following code ...
<div class="control-group">
<select multiple class="form-control" name="users">
<% User.find(function(err, musers) {
_.each(musers, function(muser) {%>
<option><%=muser.name%></option>
<% })
});%>
</select>
</div>
The .ejs view does not seem to see the content of the <%=muser.name%> variable while the server does... Any idea why?
You should not be running asynchronous code in your view. Find the users you want in your controller, then provide them to the view as view locals:
api/controllers/LabController.js:
new: function(req, res) {
User.find(function(err, users) {
if (err) {return res.serverError(err);}
return res.view({users: users});
});
}
views/lab/new.js:
<div class="control-group">
<select multiple class="form-control" name="users">
<% _.each(users, function(user) {%>
<option><%=user.name%></option>
<% }) %>
</select>
</div>
I want to insert an imege to a MVC Project, i used following code to do that,
but i want to pass that image using jquery instead of pass data using Html.BeginForm.
how can i do it,
<% using (Html.BeginForm("uploadImage", "ItemMaster", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
%>
<p><input type="file" id="fileUpload" name="fileUpload" size="23"/> </p>
<p><input type="submit" value="Upload file" /></p>
<%= Html.Hidden("hdnItemCode", null, new { style = "width:100px" })%>
<%
}
%>
If you're looking for a method to upload a file via jQuery, I suggest this question and answers.
Getting data from view to create controller in asp.net MVC
I know this is very simple but I am just learning ASP.net MVC.
I have a Create controller and a create view (used the generator)
I can hard code data into the controller and that does get saved but I want to know how to get the data the user put on the form back into the controller.
My controller is like this.
public ActionResult Create(Seller newSeller)
{
if (ModelState.IsValid)
{
try
{
newSeller.SellerID = 34324442;
newSeller.State = "NA";
newSeller.UserType = "Seller";
newSeller.FirstName = "sdfasd";
newSeller.LastName = "dasdfadsf";
newSeller.Phone = "33333";
newSeller.Email = "dfasdfasdf";
// write to database
listingsDB.Sellers.AddObject(newSeller);
listingsDB.SaveChanges();
return RedirectToAction("Details", newSeller.SellerID);
}
catch(Exception ex)
{
}
}
return View(newSeller);
}
My view looks like this
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.SellerID) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.SellerID) %>
<%: Html.ValidationMessageFor(model => model.SellerID) %>
</div>
... Lots of propterties and then
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
I am using ASP.net MVC 2 if it matters.
You usually have two actions on the controller: one for rendering the form and one for processing the posted form values. Typically it looks like this:
public class SellerController: Controller
{
// used to render the form allowing to create a new seller
public ActionResult Create()
{
var seller = new Seller();
return View(seller);
}
// used to handle the submission of the form
// the seller object passed as argument will be
// automatically populated by the default model binder
// from the POSTed form request parameters
[HttpPost]
public ActionResult Create(Seller seller)
{
if (ModelState.IsValid)
{
listingsDB.Sellers.AddObject(seller);
listingsDB.SaveChanges();
return RedirectToAction("Details", new { id = seller.SellerID });
}
return View(seller);
}
}
then your view looks as you have shown, it contains a form and input fields allowing the user to fill each property of the model. When it submits the form, the second action will be invoked and the default model binder will automatically fill the action parameter with the values entered by the user in the form.
In order to get my EF4 EntityCollection to bind with check box values, I have to manually create the check boxes in a loop like so:
<p>
<%: Html.Label("Platforms") %><br />
<% for(var i = 0; i < Model.AllPlatforms.Count; ++i)
{ %>
<%: Model.AllPlatforms[i].Platform.Name %> <input type="checkbox" name="PlatformIDs" value="<%: Model.AllPlatforms[i].Platform.PlatformID %>" /><br />
<% } %>
</p>
It works, but it doesn't automatically populate the group of check boxes with existing values when I'm editing a model entity. Can I fudge it with something like?
<p>
<%: Html.Label("Platforms") %><br />
<% for(var i = 0; i < Model.AllPlatforms.Count; ++i)
{ %>
<%: Model.AllPlatforms[i].Platform.Name %> <input type="checkbox" name="PlatformIDs" value="<%: Model.AllPlatforms[i].Platform.PlatformID %>" checked=<%: Model.GameData.Platforms.Any(p => PlatformID == i) ? "true" : "false" %> /><br />
<% } %>
</p>
I figure there has to be something along those lines which will work, and am just wondering if I'm on the right track.
EDIT: I'm purposely staying away from MVC's check box HTML helper methods as they're too inflexible for my needs. My check boxes use integers as their values by design.
Close. You'll actually want to modify your server-side code so that the "checked" attribute is not emitted at all unless you want the checkbox to be checked.
checked="true"
or
checked="false"
are technically both invalid HTML. Source.
If you want a checked checkbox, you want to emit:
checked="checked"
Any value in the quotes will actually check the box (including checked="false"), but checked="checked" is considered proper.
So, updating your code, just tweak the ternary operator to use checked='checked' or nothing at all.
<%: Model.AllPlatforms[i].Platform.Name %> <input type="checkbox" name="PlatformIDs" value="<%: Model.AllPlatforms[i].Platform.PlatformID %>" <%: Model.GameData.Platforms.Any(p => p.PlatformID == i) ? "checked='checked'" : "" %> /><br />
You're on the right track, but I think you need to modify the snipet to it to
<%: Model.GameData.Platforms.Any(p => PlatformID == i) ? "checked='true'" : string.Empty %>
I am trying out ASP.Net MVC2 by building a small sample website which, amongst other features provides the user with a 'Contact Us' page. The idea is to allow a user to enter their name, email address, message subject and message. To send the message the user clicks on an ActionLink. This is the view:
<% Html.BeginForm(); %>
<div>
<%: Html.Label("Name")%>
<br />
<%: Html.TextBox("txtName", "",new { style = "width:100%" })%>
<br />
<%: Html.Label("Email address")%>
<br />
<%: Html.TextBox("txtEmail", "", new { style = "width:100%" })%>
<br />
<%: Html.Label("Subject")%>
<br />
<%: Html.TextBox("txtSubject", "", new { style = "width:100%" })%>
<br />
<%: Html.Label("Message")%>
<br />
<%: Html.TextBox("txtMessage", "", new { style = "width:100%" })%>
</div>
<div style='text-align: right;'>
<%:
Html.ActionLink("Send", "SentEmail", new { name = Html.g, sender = "txtEmail", subject = "txtSubject", message="txtMessage" })
%>
</div>
<% Html.EndForm(); %>
The idea is once the ActionLink has been clicked a method in the controller is called into which the username, email address, subject and message will be passed. This is the method in the controller:
public ActionResult SentEmail(string name, string sender, string subject, string message)
{
//Send email here and then display message contents to user.
ViewData["Name"] = name;
ViewData["Message"] = message;
ViewData["ThankyouMessage"] = "Thank you for contacting us. We will be in touch as soon as possible.";
return View();
}
However... when I click the link the values which are passed into the method are null. I have tried creating a route to do this but it doesn't work either. Should I be using another method?
Thank you,
Morris
Actually to achieve what you want to is easier than in your sample. Never heard about Model classes, Model Binder and strong typed views? Here thery are
Model class
public class ContactUsModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Subject { get; set; }
public string Message { get; set; }
}
Then in your controller you should have two action: the first that show the form with default values and the second that receive the form with the data placed by the user. These two actions maps exactly to the HttpGet and HttPost verbs.
[HttpGet]
public virtual ActionResult ContactUs() {
ContactUsModel model = new ContactUsModel();
return View(model);
}
[HttpPost]
public virtual ActionResult ContactUs( ContactUsModel model ) {
//e.g. Save the contact request to database
}
To use this your view shal be strong typed to the ContactUsModel class
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ContactUsModel>" %>
<% using (Html.BeginForm()) { %>
<div>
<%: Html.LabelFor(model => model.Name) %><br />
<%: Html.TextBoxFor(model => model.Name, new { style = "width:100%" })%>
</div>
<div>
<%: Html.LabelFor(model => model.Email) %><br />
<%: Html.TextBoxFor(model => model.EMail, new { style = "width:100%" })%>
</div>
<div>
<%: Html.LabelFor(model => model.Subject) %><br />
<%: Html.TextBoxFor(model => model.Subject, new { style = "width:100%" })%>
</div>
<div>
<%: Html.LabelFor(model => model.Message) %><br />
<%: Html.TextAreaFor(model => model.Message, new { style = "width:100%" })%>
</div>
<div>
<input type="submit" value="Save" />
</div>
<% } %>
the magic of everything this is called ModelBinder. Please read more and more about MVC here.
The action link isn't going to trigger a http post nor will it pass in the values of your form fields, just a http get and not passing through any form data - ideally you'd use an input submit button to post the data. What is certain is that it is good practise that any request that causes creating/updating of data should be done via a http post.
Submit button would just be like.
<input type="submit" value="Send" />
You then have several ways of accessing the form data firstly you could use a FormCollection to access the data
[HttpPost]
public ActionResult SendEmail(FormCollection collection)
{
string email = collection["txtEmail"];
...
}
Secondly you could use the method parameters and rely on model binding, but you must make sure field names match the parameter name so
<%: Html.TextBox("txtEmail", "", new { style = "width:100%" })%>
...would require...
[HttpPost]
public ActionResult SendEmail(string txtEmail)
{
...
}
If this form isn't being posted to the same action thats return the view then you'd also need to change your begin form tag, ideal you should use 'using' with it as well. So you'd get:
<% using (Html.BeginForm("SendEmail", "<controller-name>"))
{ %>
.... form fields in here ...
<input type="submit" value="Send" />
<% } %>
If the button isn't suitable for your design you could use something like:
<input type="image" src="<%: Url.Content("~/Content/images/myimage.gif") %>" value="Send" />
This would have the same effect. To trigger a post from an a tag though you'd need to look at using javascript, I can't remember the exact syntax but off hand I think if you used jquery you'd be looking at something like: (form a single form page only)
Send
But then you create a dependency on javascript where as really you should try have your site degrade gracefully so it can be used by visitors with javascript disabled. There are perhaps more advanced way of achieving this whilst meeting design requirements but that can get heavily into client side code which is probably outside of what you want for your sample.