I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005.
I am using also Entity Framework and Code First Method.
In a view Index, I have a DropDownList Gamme. I define its item selected in my view, like this :
public string SelectedProfile_Ga { get; set; }
In this view, I have a button Appliquerthat took me to another view Application.
<input type="button" value="Appliquer" id="appliquer" onclick="window.location = 'ProfileGa/Application'"/>
In the view Application, I have a button submit Appliquer.
<input type="submit" value="Appliquer" id="appl" />
When I click on Appliquer, I want save the value selected in my DropDownList Gamme in my base.
The problem is that this value is passed NULL when i change the view (exit page Index and open Application).
I find that with Debugging.
The Controller action :
[HttpPost]
public ActionResult app(FlowViewModel model)
{
Famille fam = new Famille();
fam.ID_Gamme = model.SelectedProfile_Ga;
db.Familles.Add(fam);
db.SaveChanges();
return RedirectToAction("Application");
}
Note :
I didn't forget this in the Application:
<% using (Html.BeginForm("app", "ProfileGa")) { %>
ProfileGa is the name of my controller.
For starters, your dropdown is in the Index view, and the selection is happening there. Then you're redirecting to ProfileGa/Application and leaving this information behind.
I would change this button:
<input type="button" value="Appliquer" .. etc
to a <submit>, and wrap the code with the dropdown in one of these:
using (Html.BeginForm("Application", "ProfileGa")) {
and add a Post version of Application
[HttpPost]
public ActionResult Application(FlowViewModel model)
{
// Do whatever
return View(model);
}
Then when you get to the Application view, it should still have the same information as it left Index with.
To check this is working, put a breakpoint at return View(model); and look at the model's contents.
However, posting null from the view probably means that something is wrong inside your <% using (Html.BeginForm("app", "ProfileGa")) { %> statement, so if the above doesn't do anything, post the code from your `Application' view.
Related
I am trying to implement a Next button in my view to go to the next record.
When I click the button, it just keeps calling the Details action in my controller for the current item rather than the next.
So if I am looking at Sample 1 and click Next, I can see that sampleNumber is still 1 when calling Details in SampleController.
Here is the code for the button in Details.cs.html:
#{
if (Model.Pallet.Samples.Count > Model.SampleNo)
{
using (Html.BeginForm("Details", "Sample"))
{
#Html.Hidden("sampleNumber", Model.SampleNo + 1)
<input type="submit" value="Next" class="pull-right" />
}
}
}
And the Details method has the signature:
public ActionResult Details(int sampleNumber)
Any advice is much appreciated
You need to declare a new variable with
#{
var next_record = Model.SampleNo + 1;
}
and change
#Html.Hidden("sampleNumber", Model.SampleNo + 1)
to
#Html.Hidden("sampleNumber", #next_record)
By all appearances you're posting to the action Details however I'm not sure how you're passing the value to it.
So I see 2 parts to the solution.
1) You should just pass the view model to the controller action.
This has the advantage of being able to get the values, and increment the counter at the same time, removing that logic from the view.
Below, ViewModel will be the same type that is used for the #model part of the view.
public ActionResult Details(ViewModel vm)
{
// Other logic to get details
vm.SampleNo++;
return View(vm);
}
2) Your hidden field for sampleNumber is not bound to the View Model, so when you do your post, the value that is passed is Model.SampleNo not Model.SampleNo + 1 as I suspect you expect it to be.
You should change the #Html.Hidden... to #Html.HiddenFor(Model.SampleNumber) for the correct binding.
Is it possible to use Model binding to get value of a button in the POST action method when its clicked on. I have a complex type and I wanted to have the user click on a button and retrieve the value of that button so I can use it to update the value of the complex type in the DB.
Note that at this point I have already saved the entity into the database and all that is left is to get a way to update properties of the complex type.
If there is a recommended way to do that am willing to adopt that.
Thanks in advance.
You can use multiple submit buttons with different values to specify the way of update model.
#using (Html.BeginForm("MultipleCommand", "Home", FormMethod.Post, new { id = "submitForm" }))
{
.
.
.
<button type="submit" id="btnSave" name="Command" value="create">Save</button>
<button type="submit" id="btnSubmit" name="Command" value="update">Submit</button>
}
public ActionResult(ComplexModel model, string Command)
{
if(Command == "create")
{
}
else if(Command == "update")
{
}
else
{
// Default action
}
}
For more info read Handling multiple submit buttons on the same form - MVC Razor.
Do something like this
public ActionResult Index(string submit)
////Your action while clicking the button and in the view button name should be submit
{
//// The string submit will have the value of the button
}
I have created a C# ASP.NET MVC application. In the Index view, i have added 3 buttons, when each button is clicked i want to execute 3 different functions from the Index controller.
Index View that resides in the Home folder
#using (Html.BeginForm()) {
<input type="submit" value="b1" />
<input type="submit" value="b2" />
<input type="submit" value="b3" />
}
Home Controller
public ActionResult Button1Click()
{
return View();
}
public ActionResult Button3Click()
{
return View();
}
public ActionResult Button2Click()
{
return View();
}
When each button is clicked how can i write code to execute the correct controller method ?
If you are posting then you can put each button in a separate form:
#using (Html.BeginForm("Button1Click","Index")) {
<input type="submit" value="b1" />
}
#using (Html.BeginForm("Button2Click","Index")) {
<input type="submit" value="b2" />
}
#using (Html.BeginForm("Button3Click","Index")) {
<input type="submit" value="b3" />
}
If there is no data to post, as shown in your method, and you still want to have all buttons in the same form then you can do an ajax post (this does not make sense though but hey I'm basing it on the code you gave in your question), with this though you may want to change your buttons from a submit into a button (input type="button").
$("#b1").click(function(){
$.post('/index/button1click', function() {
});
});
$("#b2").click(function(){
$.post('/index/button2click', function() {
});
});
$("#b3").click(function(){
$.post('/index/button3click', function() {
});
});
If you want to do a GET instead of a post then just replace .post with .get.
In MVC you need to remove the (Asp.Net) idea of linking button clicks to actions. ASP.Net is event driven MVC uses the classic HTTP REST approach.
So the buttons aren't actions, the buttons submit actions. The action that is submitted is controlled by your form. So your form POSTs data to the controller, using a HTTP post.
Now it's not clear what your trying to achieve here. You appear to be returning different views from each action. So using the REST idea, you should be a GETing not a POSTing (your getting HTML). So the simplest idea is to turn your input(submit) into Anchor tag, i.e. a HTTP GET:
#Html.ActionLink("Button1Click")
etc.
MVC doesn't work like Webforms where you have a ButtonClick event.
Do you want to post any values to the controller?
If not, you can use a link that you can style like a button. Use the buildin Html extensions.
//For links
#Html.ActionLink("Button1Text","Button1Click")
#Html.ActionLink("Button2Text","Button2Click")
#Html.ActionLink("Button3Text","Button3Click")
//If you need more styling options
Button1
Button2
Button3
That way you don't need any javascript or multiple forms in your view. You'll have to add some styling in your CSS files.
One easy way to execute different actions on different button within the same form is to distinguish button click by their name:
Example code is:
View:
#using (Html.BeginForm("MyMethod","Controller"))
{
<input type="submit" value="b1" name="b1" />
<input type="submit" value="b2" name="b2" />
<input type="submit" value="b3" name="b3" />
}
Controller:
[HttpPost]
public ActionResult MyMethod(string b1, string b2, string b3)
{
if (b1 != null)
{
return Button1Click();
}
else if (b2 != null)
{
return Button2Click();
}
else
{
return Button3Click();
}
}
public ActionResult Button1Click()
{
return RedirectToAction("Index");
}
public ActionResult Button3Click()
{
return RedirectToAction("Index");
}
public ActionResult Button2Click()
{
return RedirectToAction("Index");
}
I have an ASP.NET MVC application that displays a list of items. In my view page I loop over the items and render each item with partial view, like so:
#foreach(var item in Model.items)
{
<li>
#Html.Partial("ItemView", item)
</li>
}
In the item view, I wrap each item with a form that has a 'Delete' button, like this:
#using(Html.BeginForm(...))
{
#Html.HiddenFor(m=>m.Id)
<label>#Model.Name (#Model.Id)</label>
<input type="submit" value="Delete"/>
}
The items are rendered properly, the resulting page has a nice list of all the items with their proper names and IDs displayed.
EDIT: The same happens with #Hidden, apparently, contrary to what I wrote before.
In addition, this only happens the second time the form is rendered (that is, after one of the Delete buttons is clicked), the first time everything is working properly. My action methods looks like this:
public ActionResult AllItems()
{
var model = new AllItemsModel();
return PartialView(model);
}
public ActionResult Delete(DeleteModel model)
{
.... Perform the delete ...
return PartialView("AllItems", new AllItemsModel());
}
Why is this happening?
I suspect that this happens because you already have an Id parameter in your RouteData:
public ActionResult SomeAction(int id)
{
var model = ...
return View(model);
}
and you have requested the page with /somecontroller/someaction/123. The HiddenFor helper now uses the Id from the route values and not the id of the item. Try renaming the property on your item view model to something different than id. For example ItemId.
Another possibility is that the problem occurs only after the postback and not when the page is initially rendered. Showing your POST action might help in exploring this possibility further.
UPDATE:
Alright, now that you have shown your POST action things are much more clear:
public ActionResult Delete(DeleteModel model)
{
.... Perform the delete ...
return PartialView("AllItems", new AllItemsModel());
}
you are basically creating a new view model here and passing it to the partial view. But HTML helpers always use the value from the ModelState when binding. And only after that the value from your view model. So if you intend to modify properties on your model inside your POST action make sure that you have removed this value from the ModelState first. In your example since you have completely scratched the entire view model (by creating a new AllItemsModel()) you could clear the entire ModelState:
public ActionResult Delete(DeleteModel model)
{
.... Perform the delete ...
// Clear the modelstate otherwise the view will use the values that were initially posted
// and not the values from your view model
ModelState.Clear();
return PartialView("AllItems", new AllItemsModel());
}
This behavior is by design and applies to all HTML helpers, not only the HiddenFor helper.
I have a dropdownlist that is being populated by a sql server, I am using Visual Studio 2010, cshtml, with razor as well as using the MVC pattern to create this project. What I am trying to do is when someone selects a value from the dropdown list on change it will update the page with information about that book.
I need help with the three things below:
user selects a book from the dropdownlist how to get the Book Name back to the controller
The server (retrieve the information from the server about the book) and
Back to view to be displayed.
I started with getting the dropdown poplulated.
My View looks like this
BookName: #Html.DropDownList("BookName", ViewData["BookName"] as IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })
My Controller:
public ActionResult Index()
{
ViewData["BookName"] = new SelectList(_context.BookName.Select(a => a.Book_Name).Distinct());
return View();
}
A dropdown list can't cause the page to post back to your controller on its own. You need to do one of two things:
Add a submit button so that the user changes the dropdown and then clicks a button to view the results.
Use javascript to submit the form on the element's change event.
Either way, you will need to wrap the dropdown/submit button in a form.
Option 1
<form>
BookName: #Html.DropDownList("BookName", ViewData["BookName"] as IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })
<input type="submit" value="Show results" />
</form>
Option 2
<script type="text/javascript">
// assuming you're using jQuery
$(function() {
$('#UserSelectedValue').change(function() {
$(this).parent('form').submit();
});
});
</script>
<form>
BookName: #Html.DropDownList("BookName", ViewData["BookName"] as IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })
<input type="submit" value="Show results" />
</form>
Your controller code would then become something like:
public ActionResult Index(string bookName)
{
ViewData["BookName"] = new SelectList(_context.BookName.Select(a => a.Book_Name).Distinct());
if (!string.IsNullOrWhiteSpace(bookName))
{
ViewData["Books"] = _context.BookName.Where(b => b.Book_Name == bookName).ToList();
}
return View();
}