How to pass both model value & text value to controller in mvc? - asp.net-mvc-3

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...

Related

how to pass parameters to controller from view

I need to pass parameters from a view to control in a form. These parameters are for example a string that is not in a textField. The string is "FATHER" and I send this string from the view to the controller when I click on the submit button in the form. Anyone can suggest how I can do it?
add a hidden input field to your form with a value of "FATHER":
<?= form_hidden('name_of_field', 'FATHER') ?>
and in your controller, get the value when the form is submitted:
$value = $this->input->post('name_of_field');
So if this question is about asp.net MVC ... :
Are you using a strongly typed view, do you have a ViewModel? If so, add a property of type string, say StringToHide, to it, set it to "FATHER" and then, in your form, add
#Html.HiddenFor(StringToHide)
Then the information will be passed to the controller, but it is not editable by the user. And if you're not using a viewmodel yet, well, then you should. It's a clean way to compose all your data when passing from views to controllers and vice versa.
Assuming Asp.net MVC
In View
#{ Html.RenderAction("Menu", "", new { parameterFromView= "FATHER" }); }
In Controller
[HttpPost]
public ActionResult Menu(string parameterFromView)
{
// do whatever
}
In jquery call append the text Father to the URL and accept it in controller.
see code below.
$("#submit").click(funtion(){
window.url = "Controller/Action/" + "Father";
});

How to save checkbox checked values in Database [duplicate]

I have a simple mvc project consisting of one table named Persons and that table has some attributes like name, age, surname and so on.
I Recently added an attribute to table which is type of bit in SQL and bool in C# and for me it represents some status. If it is ok I put that status to true or false.
In one controller I create an index view of my Persons in the database and I display the status as a checkbox. That is working ok. What I want to do is to change the status if I click on that checkbox instead of using an edit view for all of the atributes.
I just want to save checkbox value from my index view to database.
Some people advised me to create an action in my controller like so:
public ActionResult Save(int id, bool status){}
Where id is id of my person in db and status is a value of the checkbox I clicked.
So how do I call that function with jquery, ajax or javascript and send those params?
I am not so good with ajax and a little bit afraid of it :)
And one more thing I manage to show checkbox value corectly from my databse only in this way:
#Html.CheckBox("somename", item.Status)
<input name="somename" type="hidden" value="false"/>
Any help or advice or sending me to good direction is good!
You have several options. One way would be to place the checkboxes in a (normal) form and then use the jQuery Form plugin to Ajaxify the form:
#using(Html.BeginForm()) {
#Html.Checkbox(...)
}
<script type="text/javascript">
$(document).ready(function () {
$('form').ajaxForm({
success: Saved,
error: HandleError
});
});
function Error(response, status, err) {
// code to handle error here
}
function Saved(responseText, statusText, xhr, $form) {
// code to handle succes, if any
}
</script>
You could, of course, use an #Ajax.BeginForm as well, but this has the advantage of being easily downgradable. Just remove the jQuery form initialisation and you got yourself a regular form : )
Another possibility is to simply use an #Ajax.ActionLink. I wrote a blog post on how to deal with Ajax.ActionLink that I think will help you out.
The signature for your controller action on your question looks correct:
public ActionResult Save(int id, bool status){}
Another options is actually to create a Settings view model (call it what you will), and in there just have a bunch of bool properties to represent the checkboxes:
public class Settings
{
public bool Status { get; set; }
// more properties here
}
then you can bind your action to the Settings object:
public ActionResult Save(int id, Settings settings){}
This will come in handy in case you end up having multiple checkboxes to bind.

MVC 3 POST data and the Id field

I have a strongly typed razor view for a model in my MVC 3 project. Basically its for editing the model.
The model contains an Id field for the database key and some other string fields (Its a viewModel and all but thats not the point of the question).
In the view I just have a form and a submit button and nothing else. When the View is posted to the controller the model in the controller has all fields empty EXCEPT for the Id field which seems to have been auto-magically filled up.
How and where does the Id field gets populated in the model without there being a corresponding 'input' element for it in the view.
This is probably a dumb question but I would appreciate even just a link to what I should read up on. Thanks.
I bet it comes from the url as route parameter.
For example you have the following controller:
public class HomeController: Controller
{
public ActionResult Index(int id)
{
vqr model = GetModel(id);
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// the model.Id property will be automatically populated here
// because the request was POST /home/index/123
...
}
}
and the following view:
#model MyViewModel
#using (Html.BeginForm())
{
<button type="submit">OK</button>
}
Now you navigate to GET /home/index/123 and you get the following markup:
<form action="/home/index/123" method="post">
<button type="submit">OK</button>
</form>
Notice the action attribute of the form? That's where the id comes from. Basically the Html.BeginForm() helper uses the current url when generating the action attribute, and since the current url is /home/index/123 it is what gets used.
And because if you have left the default routes in your Global.asax, the {id} route token is used at the end of the url, the default model binder successfully binds it to the Id property of your view model.
You are probably hitting a URL similar to the following: /MyObject/Edit/15
This is then returning the page that you have your blank form on.
What happens next is you have an HTML.BeginForm() which is posting BACK to /MyObject/Edit/15
Now because of the post back having the same format your routing rules are picking up the '15' and binding it back to your id.
Have you added the ID field as a hidden field?
e.g.
#Html.HiddenFor(x=> x.ID)

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 });
}

Best method to pass value in MVC

I am still new to MVC, so sorry if this is an obvious question:
I have a page where the user can choose one of several items. When they select one, they are taken to another form to fill in their details.
What is the best way to transfer that value to the form page?
I don't want the ID of the item in the second (form) pages URL.
so it's /choose-your-item/ to /redemption/ where the user sees what was selected, and fills the form in. The item selected is displayed, and shown in a hidden form.
I guess one option is to store in a session before the redirect, but was wondering if there was another option.
I am using MVC3
Darin Dimitrov's answer would be best if you don't need to do any additional processing before displaying the /redemption/ page. If you do need to some additional processing, you're going to have to use the TempDataDictionary to pass data between actions. Values stored in the TempDataDictionary lasts for one request which allows for data to be passed between actions, as opposed to the values stored in the ViewDataDictionary which only can be passed from an action to a view. Here's an example below:
public ActionResult ChooseYourItem()
{
return View();
}
[HttpPost]
public ActionResult ChooseYourItem(string chosenItem)
{
TempData["ChosenItem"] = chosenItem;
// Do some other stuff if you need to
return RedirectToAction("Redemption");
}
public ActionResult Redemption()
{
var chosenItem = TempData["ChosenItem"];
return View(chosenItem);
}
If you don't want the selected value in the url you could use form POST. So instead of redirecting to the new page, you could POST to it:
#using (Html.BeginForm("SomeAction", "SomeController"))
{
#Html.DropDownListFor(...)
<input type="submit" value="Go to details form" />
}
To help others, this is how I resolved my issue of needing multiple buttons posting back, and wanting to pass a different Id each time.
I have a single form on the page, that posts back to my controller:
The Form:
#using (Html.BeginForm("ChooseYourItem", "Item", FormMethod.Post))
{
And the code
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChooseYourItem(string itemId)
{
TempData["ITEMID"] = itemId
return RedirectToAction("Create", "Redemption");
}
Then, inside the form, I create buttons whose name == "itemId", but has a different value each time.
For example
<strong>Item 1</strong>
<button value="123" name="itemid" id="btn1">Select</button>
<strong>Item 2</strong>
<button value="456" name="itemid" id="btn2">Select</button>

Resources