Use DELETE form method in Html.BeginForm()? - asp.net-mvc-3

I'd like to use the appropriate HTTP method when possible. In this case, when a button is clicked to delete something, I want to fire the controller action with the attribute [HttpDelete]. However, I can't seem to create a form with this method - using Razor syntax. The FormMethod enum does not have an option for Delete and doing the following doesn't override it:
#using (Html.BeginForm("Order", "Users", FormMethod.Post, new { method = "DELETE" }))
Searching for solutions yields none, is nobody doing this? I know I can just use POST but isn't this the point of the HTTP delete method to begin with?

You need this in your form:
#using (Html.BeginForm("Order", "Users"){
#Html.HttpMethodOverride(HttpVerbs.Delete)
}

Related

Regarding loading of partial view in mvc

i am new in mvc. now learning. i was searching various technique to load partial view in mvc and i got good one in stackoverflow. here it is.
If you want to load the partial view directly inside the main view you could use the Html.Action helper:
#Html.Action("Load", "Home")
or if you don't want to go through the Load action use the HtmlPartial hepler:
#Html.Partial("_LoadView")
If you want to use Ajax.ActionLink, replace your Html.ActionLink with:
#Ajax.ActionLink(
"load partial view",
"Load",
"Home",
new AjaxOptions { UpdateTargetId = "result" }
)
and of course you need to include a holder in your page where the partial will be displayed:
<div id="result"></div>
Also don't forget to include:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
in your main view in order to enable Ajax.* helpers. And make sure that unobtrusive javascript is enabled in your web.config (it should be by default):
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
after going through the above code one confusion occur. help require. my confusion as below.
#Html.Action("Load", "Home")
#Html.Partial("_LoadView")
i know the use of #Html.Partial("_LoadView") but do not understand how #Html.Action("Load", "Home") will work ?
can anyone show me couple of example to show the various usage of
#Html.Action("Load", "Home")
and how it is different from #Html.Partial("_LoadView")
thanks
Html.Partial
Renders the partial view as an HTML-encoded string.
This method result can be stored in a variable, since it returns string type value.
Simple to use and no need to create any action.
Partial method is useful used when the displaying data in the partial view is already in the corresponding view model.For example : In a blog to show comments of an article, we would like to use RenderPartial method since an article information with comments are already populated in the view model.
#Html.Partial("_Comments")
Html.Action
Renders the partial view as an HtmlString .
For this method, we need to create a child action for the rendering the partial view.
This method result can be stored in a variable, since it returns string type value.
Action method is useful when the displaying data in the partial view is independent from corresponding view model.For example : In a blog to show category list on each and every page, we would like to use Action method since the list of category is populated by the different model.
#{Html.Action("Category","Home");}
#Html.Action("Load", "Home")
Will execute the "Load" ActionResult in your "HomeController".
This Action may return any of these (ref: MSDN):
ContentResult
EmptyResult
FileResult
HttpUnauthorizedResult
JavaScriptResult
JsonResult
RedirectResult
RedirectToRouteResult
ViewResultBase
While
#Html.Partial("_LoadView")
Will insert your partial view "_LoadView" into your current view.
If you're familiar with web forms, think of your partial views as .ascx (user controls).
Edit:
Example of usage of #Html.Action():
Say you have this view:
<p>Here is my name: #Html.Action("Name")</p>
And this is my controller (As you see, I use the overload of Html.Action() that implicit uses the controller you're routed to):
public class FooController : Controller
{
//
// GET: /Foo/
public ActionResult Index()
{
return View();
}
// GET: /Foo/Name
public ActionResult Name()
{
return Content("Annish");
}
}

How can I add a class attribute to Html.BeginForm() in MVC3/4 preserving the minimal overload

I'm in the process of upgrading my app to Bootstrap 2.1.1 and I need to add a class attribute (class="form-horizontal") to many of the form tags. The problem is, most of the forms use the rather beautiful
#using (Html.BeginForm()) {
format which I'd rather keep. The obvious way to get the class attribute in there is to use the following overload, for example:
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal" })) {
But I'd rather not do that. What is the best way to add a class attribute to my form?
I've thought about using a jQuery document ready handler to .addClass("form-horizontal") to forms, but am worried that users would see the dreaded 'flash of unstyled content'.
Another approach might be to use a less-style mix-in, to add the .form-horizontal class to all form style rules but I haven't used less yet, so I'm not sure about this one.
Anyone know the best way to solve this problem?
Following StanK's advice, and the advice of some other answers on SO, I created an extension method specifically tailored to that Bootstrap form layout:
public static MvcForm BeginHorizontalForm(this HtmlHelper helper) {
return helper.BeginForm(null, null, FormMethod.Post, new { #class = "form-horizontal" });
}
which allows me to use
#using (Html.BeginHorizontalForm()) {...
which is nice and elegant.
What about writing a custom helper method which calls the overload required, passing in 'form-horizontal'?
Then, you views would use #using (Html.BootstrapBeginForm()) {, leaving you views nice and tidy.

Retrieve form data in action method : ASP.NET MVC 3

I am trying to use a simple form with only a text field to get some information that will be used in an action method to redirect to a different action method. Here's the context:
I have a route mapped in my global.asax.cs file which prints "moo" the given amount of times. For example, if you typed "www.cows.com/Moo8", "Moo" would be printed 8 times. The number is arbitrary and will print however many "Moo"s as the number in the URL. I also have a form on the homepage set up as follows:
#using (Html.BeginForm("Moo", "Web"))
{
<text>How many times do you want to moo?</text>
<input type="text" name="mooNumber" />
<input type="submit" value="Moo!" />
}
The number submitted in the form should be sent to the action method "Moo" in the "Web" controller (WebController.cs):
[HttpPost]
public ActionResult Moo(int mooNumber)
{
Console.WriteLine(mooNumber);
return RedirectToAction("ExtendedMoo", new { mooMultiplier = mooNumber });
}
Finally, the "Moo" action method should send me back to the original "www.cows.com/Moo8" page; as you can see above I simply used an already existing action method "ExtendedMoo":
public ViewResult ExtendedMoo(int mooMultiplier)
{
ViewBag.MooMultiplier = RouteData.Values["mooMultiplier"];
return View();
}
How can I access the value submitted in my form and use it in the last call to "ExtendedMoo"?
Refer to this post or this, you might get some idea how routing works. Something is wrong with "www.cows.com/Moo8", try to find it out. Hint "{controller}/{action}/{parameter_or_id}"
Instead of RedirectToAction, use Redirect and create the Url.
This should do the trick:
return Redirect(Url.RouteUrl(new { controller = "Web", action = "ExtendedMoo", mooMultiplier = mooNumber }));
I hope i helps.
Oh wow. Turns out that form was on my Homepage, so instead of using "Moo" as the action method, I needed to override the "Homepage" action method with a [HttpPost] annotation over THAT one. Didn't realize that forms submitted to the page they were rendered from - that was a really useful piece of information in solving this problem!
Thanks all for your attempts at helping out!
If I understood right
You can you use form Collection to get the value from textbox.
Make Sure the input tag has both id and name properties mentioned otherwise it wont be available in form collection.
[HttpPost]
public ActionResult Moo(int mooNumber, **formcollection fc**)
{
**string textBoxVal= fc.getvalue("mooNumber").AttemptedValue;**
Console.WriteLine(mooNumber);
return RedirectToAction("ExtendedMoo", new { mooMultiplier = mooNumber });
}

How to pass both model value & text value to controller in mvc?

I want to pass two values from view to controller . i.e., #Model.idText and value from textbox. here is my code:
#using HTML.BeginForm("SaveData","Profile",FormMethod.Post)
{
#Model.idText
<input type="text" name="textValue"/>
<input type="submit" name="btnSubmit"/>
}
But problem is if i use "Url.ActionLink() i can get #Model.idText . By post action i can get textbox value using FormCollection . But i need to get both of this value either post or ActionLink
using ajax you can achieve this :
don't use form & declare your attributes like this in tags:
#Model.idText
<input type="text" id="textValue"/>
<input type="submit" id="btnSubmit"/>
jquery:
$(function (e) {
// Insert
$("#btnSubmit").click(function () {
$.ajax({
url: "some url path",
type: 'POST',
data: { textField: $('#textValue').val(), idField: '#Model.idText' },
success: function (result) {
//some code if success
},
error: function () {
//some code if failed
}
});
return false;
});
});
Hope this will be helpful.
#using HTML.BeginForm("SaveData","Profile",FormMethod.Post)
{
#Html.Hidden("idText", Model.idText)
#Html.TextBox("textValue")
<input type="submit" value="Submit"/>
}
In your controller
public ActionResult SaveData(String idText, String textValue)
{
return null;
}
I'm not sure which part you are struggling with - submitting multiple values to your controller, or getting model binding to work so that values that you have submitted appear as parameters to your action. If you give more details on what you want to achieve I'll amend my answer accordingly.
You could use a hidden field in your form - e.g.
#Html.Hidden("idText", Model.idText)
Create a rule in global.asax and than compile your your with params using
#Html.ActionLink("My text", Action, Controller, new { id = Model.IdText, text =Model.TextValue})
Be sure to encode the textvalue, because it may contains invalid chars
Essentially, you want to engage the ModelBinder to do this for you. To do that, you need to write your action in your controller with parameters that match the data you want to pass to it. So, to start with, Iridio's suggestion is correct, although not the full story. Your view should look like:
#using HTML.BeginForm("SaveData","Profile",FormMethod.Post)
{
#Html.ActionLink("My text", MyOtherAction, MaybeMyOtherController, new { id = Model.IdText}) // along the lines of dommer's suggestion...
<input type="text" name="textValue"/>
<input type="submit" name="btnSubmit"/>
#Html.Hidden("idText", Model.idText)
}
Note that I have added the #Html.Hidden helper to add a hidden input field for that value into your field. That way, the model binder will be able to find this datum. Note that the Html.Hidden helper is placed WITHIN your form, so that this data will posted to the server when the submit button is clicked.
Also note that I have added dommer's suggestion for the action link and replaced your code. From your question it is hard to see if this is how you are thinking of passing the data to the controller, or if this is simply another bit of functionality in your code. You could do this either way: have a form, or just have the actionlink. What doesn't make sense is to do it both ways, unless the action link is intended to go somewhere else...??! Always good to help us help you by being explicit in your question and samples. Where I think dommer's answer is wrong is that you haven't stated that TextValue is passed to the view as part of the Model. It would seem that what you want is that TextValue is entered by the user into the view, as opposed to being passed in with the model. Unlike idText that IS passed in with the Model.
Anyway, now, you need to set up the other end, ie, give your action the necessary
[HttpPost]
public ActionResult SaveData(int idText, string textValue) // assuming idText is an int
{
// whatever you have to do, whatever you have to return...
}
#dommer doesn't seem to have read your code. However, his suggestion for using the Html.ActionLink helper to create the link in your code is a good one. You should use that, not the code you have.
Recapping:
As you are using a form, you are going to use that form to POST the user's input to the server. To get the idText value that is passed into the View with the Model, you need to use the Html.Hidden htmlhelper. This must go within the form, so that it is also POSTed to the server.
To wire the form post to your action method, you need to give your action parameters that the ModelBinder can match to the values POSTed by the form. You do this by using the datatype of each parameter and a matching name.
You could also have a complex type, eg, public class MyTextClass, that has two public properties:
public class MyTextClass
{
public int idText{get;set}
public string TextValue{get;set;}
}
And then in your controller action you could have:
public ActionResult SaveData(MyTextClass myText)
{
// do whatever
}
The model binder will now be able to match up the posted values to the public properties of myText and all will be well in Denmark.
HTH.
PS: You also need to read a decent book on MVC. It seems you are flying a bit blind.
Another nit pick would be to question the name of your action, SaveData. That sounds more like a repository method. When naming your actions, think like a user: she has simply filled in a form, she has no concept of saving data. So the action should be Create, or Edit, or InformationRequest, or something more illustrative. Save Data says NOTHING about what data is being saved. it could be credit card details, or the users name and telephone...

Asp MVC ajax dynamic parameters

I'm not sure how to phrase this one but here goes nothing.
I have a controller that has two parameters: FindingId, TagId
public JsonResult Add(int FindingId, int TagId)
I have an Ajax ActionLink to call it:
<%: Ajax.ActionLink( "Add", "Add", "FindingTag",
new { FindingId = Model.FindingId },
new AjaxOptions {
HttpMethod = "Post"
})
%>
I then have a dropdownlist of available Tags:
<%: Html.DropDownListFor(m => m, Model.AvailableTags, "Select Option..", new { id = "finding_" + Model.FindingId + "_AvailableTags" } )%>
The parameters are populated in the following way:
You can see above that I am filling in the FindingId when the model is being rendered since that will always be the same in this subsection. This view is being rendered multiple times for different Findings so that FindingId will change per model.
The TagId however should come from the selected value of the DropDownList.
I am not mapping this particular request to a viewmodel to pass in so the dropdownlist is not being bound to a particular property. I have also created a route for
/FindingTag/Add/{FindingId}/{TagId}
So here are the questions this has opened and I'm really hoping someone can help me out as this stuff is really knew to me.
1) I found that the href is being rendered as Add?FindingId=## and I was curious if I can force that to render to Add/##
2) Is there an easier way I can get the value from the dropdownlist to append to the href to create the route mentioned above?
Most of the time in the project I have been using jQuery for my ajax calls so I would just manually build a URL from scratch, but I was really hoping to use the MS versions for practice. Does this seem irrational? Let me know if you have any suggestions or insight..
Edit:
I am not sure if this is the way to go about this. I am finding people saying to use a form and submit that, but if I have this as a subsection of an already strongly-typed partial view, how do I get the values to be sent back in a form I can use that isn't the fullfledged model? I would prefer to keep it to the 2 parameters and not a complex object if possible.

Resources