MVC3: button to send both form (model) values and an extra parameter - asp.net-mvc-3

In an MVC3 project, i use an Html.BeginForm to post some (model-)values. Along with those i want to send an extra parameter that is not part of the form (the model) but in the ViewBag. Now, when i use a Button (code in answer here: MVC3 razor Error in creating HtmlButtonExtension), all the form values are posted but the extra parameter remains null. When i use an ActionLink, the parameter is posted but the form values are not :) Any know how i can combine the two? Thanks!
#Html.Button("Generate!", new { id = ViewBag.ProjectID })
#Html.ActionLink("Generate!", "Post", new { id = #ViewBag.ProjectID })

My advice would be to declare a new Object in your App.Domain.Model something like this
namespace App.Domain.Model
{
public class CustomEntity
{
public Project projectEntity { get; set; }
public int variableUsed { get; set; }
}
}
In your view you can acces them easily by using CustomEntity.projectEntity and CustomEntity.variableUsed.
Hope it helps

You can do something like below.
View code
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { #id = "frmId", #name = "frmId" }))
{
#*You have to define input as a type button not as a sumit. you also need to define hidden variable for the extra value.*#
<input type="hidden" name="hndExtraParameter" id="hndExtraParameter" />
<input value="Submit" type="button" id="btnSubmit" onclick="UpdateHiddenValue()" />
}
<script type="text/javascript">
function ValidateUser() {
$("#hndExtraParameter").val('Assignvaluehere');
$("#frmId").submit();
}
</script>
Controller Code
[HttpPost]
public ActionResult ActionName(Model model, string hndExtraParameter)
{
//Do your operation here.
}

Related

Validation in mvc4 not taking place

MODEL
public class SearchTerm
{
[Required(ErrorMessage="please enter")]
public string SearchTrm { get; set; }
}
View
#using (#Html.BeginForm())
{
#Html.ValidationSummary();
#Html.AntiForgeryToken();
....
#Html.TextBoxFor(m=>m.SearchTrm)</span>
<input type="submit" value="Search"/>
#Html.ValidationMessageFor(m=>m.SearchTrm)
#using (Html.BeginForm("Search","Home"))
{
#Html.DropDownList("SelectedFieldId", new SelectList(Model.Fields, "FieldID", "NiceName", Model.SelectedFieldId));
}
}
controller
[HttpPost]
public ActionResult Search(SearchTerm Model)
{
// some code here....
}
When i click a empty search I want the validation message to take place but instead page is getting postback and i am having NullReferenceException
Mention the script name, #section scripts { ...} and check whether jqueryval has 2 files - ~/scripts/jquery.validate.min.js","~/scripts/jquery.validate.unobtrusive.min.js","~/scripts

asp.net mvc3 c# checkbox with NO binding to database

I`m using these checkboxes in my view:
<input type="checkbox" value="1" name="reglist" id="prueba2" />
<input type="checkbox" value="2" name="reglist" id="prueba3" />
I`m using entity framework and My viewModel table does not contain values for those checkbox.
I need to get the checkbox checked in the controller and keep the ones that were checked previously along requests without binding the chexboxes to classes.
Just so that we're speaking the same language, I typically refer to the things that I save in the database as the "model" and what I use as the model on the view as the "view model".
In that, I would have a model as such:
public class Person{
// properties
}
And then I would have a view model like so:
public class PersonViewModel{
public Person Person { get; set; }
public bool OtherNeededValue1 {get; set;}
public bool OtherNeededValue2 {get; set;}
}
Now, on your view, user PersonViewModel as the model. Then, in your controller, your action will look like this:
public ActionResult Create (PersonViewModel viewModel)
{
if (viewModel.OtherNeededValue1)
{
// do something
}
var p = new Person {
FirstName = viewModel.Person.FirstName
};
}
This way you don't cloud your model with unnecessary properties, but you can still take advantage of the rich binding of MVC.
Cheers.
You can make an AJAX call to your controller every time a checkbox is clicked.
Ajax Call
$(function () {
$(':checkbox').change(function () {
$.ajax({
url: '#Url.Action("CheckBoxStatus")',
type: 'POST',
data: { isChecked: $(this).is(':checked'),
id: $(this).val()
},
success: function (result) { }
});
});
});
this will send the status and the value of the checkbox to the controller and the you can store the info in whatever way like.
Controller Method
public void CheckBoxStatus(bool isChecked, int id)
{
// Do what you like here
}

MVC3 Postback doesn't have modified data

So I have the following code:
#model Project.Models.ViewModels.SomeViewModel
#using (Html.BeginForm("SomeAction", "SomeController", new { id = Model.Id}))
{
for(int i = 0; i < Model.SomeCollection.Count(); i++)
{
#Html.HiddenFor(x => Model.SomeCollection.ElementAt(i).Id)
<div class="grid_6">
#Html.TextAreaFor(x => Model.SomeCollection.ElementAt(i).Text, new { #style = "height:150px", #class = "grid_6 input" })
</div>
}
<div class="grid_6 alpha omega">
<input type="submit" value="Next" class="grid_6 alpha omega button drop_4 gravity_5" />
</div>
}
On the Controller Side I have the following:
[HttpPost]
public ActionResult SomeAction(int id, SomeViewModel model)
{
return PartialView("_SomeOtherView", new SomeOtherViewModel(id));
}
My View Model is set up like this:
public class SomeViewModel
{
public SomeViewModel()
{
}
public IEnumerable<ItemViewModel> SomeCollection { get; set; }
}
public class ItemViewModel{
public ItemViewModel(){}
public int Id {get;set;}
public string Text{get;set;}
}
The SomeCollection is always empty when SomeAction if performed. What do I have to do in order to show the updated values by users. Text Property and Id field.
Use an EditorTemplate
Create an EditorTemplate folder under your Views/YourcontrollerName and create a view with name ItemViewModel.cshtml
And Have this code in that file
#model Project.Models.ViewModels.ItemViewModel
<p>
#Html.EditorFor(x => x.Text)
#Html.HiddenFor(x=>x.Id)
</p>
Now from your Main view, call it like this
#model Project.Models.ViewModels.SomeViewModel
#using (Html.BeginForm("SomeAction", "Home", new { id = Model.Id}))
{
#Html.EditorFor(s=>s.SomeCollection)
<div class="grid_6 alpha omega">
<input type="submit" value="Next" class="grid_6 alpha omega button drop_4 gravity_5" />
</div>
}
Now in your HTTPPOST method will be filled with values.
I am not sure what you want to do with the values( returning the partial view ?) So not making any comments about that.
I am not sure you have posted all the code.
Your action method does not do anything, since it returns a partial view (for some reason from a post call, not an ajax request) using a new model object.
Your effectively passing a model back to the action and then discarding it, and returning a new model object. This is the reason your collection is always empty, its never set anywhere.
Well, for one thing, why do you have both the model AND id, a property of model, sent back to the controller? Doesn't that seem a bit redundant? Also, you're using a javascript for loop in the view. It'd be much easier to just use #foreach.
Anyway, your problem is that when you tell an action to accept a model, it looks in the post for values with keys matching the names of each of the properties of the model. So, lets say we have following model:
public class Employee
{
public string Name;
public int ID;
public string Position;
}
and if I'm passing it back like this:
#using(Html.BeginForm("SomeAction", "SomeController"))
{
<input type="text" name = "name" [...] /> //in your case HtmlHelper is doing this for you, but same thing
<input type="number" name = "id" [...] />
<input type="submit" name = "position" [...] />
}
To pass this model back to a controller, I'd have to do this:
Accepting a Model
//MVC matches attribute names to form values
public ActionResult SomethingPosted(Employee emp)
{
//
}
Accepting a collection of values
//MVC matches parameter names to form values
public ActionResult SomethingPosted(string name, int id, string postion)
{
//
}
or this:
Accepting a FormCollection
//same thing as first one, but without a strongly-typed model
public ActionResult SomethingPosted(FormCollection empValues)
{
//
}
So, here's a better version of your code.
Your new view
#model Project.Models.ViewModels.SomeViewModel
#{
using (Html.BeginForm("SomeAction", "SomeController", new { id = Model.Id}))
{
foreach(var item in Model)
{
#Html.HiddenFor(item.Id)
<div class="grid_6">
#Html.TextAreaFor(item.Text, new { #style = "height:150px", #class = "grid_6 input" })
</div>
}
<div class="grid_6 alpha omega">
<input type="submit" value="Next" class="grid_6 alpha omega button drop_4 gravity_5" />
</div>
}
}
Your new action
[HttpPost]
public ActionResult SomeAction(int Id, string Text)
{
//do stuff with id and text
return PartialView("_SomeOtherView", new SomeOtherViewModel(id));
}
or
[HttpPost]
public ActionResult SomeAction(IEnumerable<ItemViewModel> SomeCollection) //can't use someviewmodel, because it doesn't (directly) *have* members called "Id" and "Text"
{
//do stuff with id and text
return PartialView("_SomeOtherView", new SomeOtherViewModel(id));
}

how can i transfer information of one view to another?

i have designed a view in asp .net mvc3 off course registration form. This is very simple form having name ,father name , qualification and a submit button , after pressing submit button i want to display information by using another view. please suggest me how can i send information from one view to another view.
my controller class is :
namespace RegistrationForm.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
// ViewBag.Message = "Welcome to ASP.NET MVC!";
//return View();
return RedirectToAction("registrationView");
}
public ActionResult About()
{
return View();
}
public ActionResult registrationView()
{
return View();
}
}
}
my view is :
#{
Layout = null;
}
registrationView
Enter Name
</td>
<tr>
<td>
Enter Father Name
</td>
<td>
<input type="text" name="fname" id="fname" />
</td>
<tr>
<td>
Enter Qualification
</td>
<td>
<input type="text" name="qly" id="qly" />
</td>
</tr>
</table>
<input type="submit" value="submit" />
</div>
well, we faced this problem before, and the best way to get this to work was to define a model that this page will work with, then use this model object when posting back, or redirecting to another view.
for your case, you can simply define this model in your Models folder
ex: RegistrationModel.cs file, and define your required properties inside.
after doing so, you will need to do 2 more steps:
1- in your GET action method, create a new RegistrationModel object, and provide it to your view, so instead of:
return View();
you will need something like:
var registrationModel = new registrationModel();
return View(registrationModel);
2- Use this model as a parameter in your POST Action method, something like
[HttpPost]
public ActionResult registrationView(RegistrationModel model)
{
// your code goes here
}
but don't forget to modify the current view to make use of the provided model. a time-saver way would be to create a new dummy View, and use the pre-defined template "Create" to generate your View, MVC will generate the properties with everything hooked up. then copy the generated code into your desired view, and omit any unneeded code.
this is a Pseudo reply. if you need more code, let me know
<% using Html.Form("<ActionName>") { %>
// utilize this HtmlHelper action to redirect this form to a different Action other than controller that called it.
<% } %>
use ViewData to store the value.
just remember that it will only last per one trip so if you try to call it again, the value would have been cleared.
namespace RegistrationForm.Controllers { public class HomeController : Controller { public ActionResult Index() { // ViewBag.Message = "Welcome to ASP.NET MVC!";
ViewData["myData"] = "hello world";
//return View();
return RedirectToAction("registrationView");
}
public ActionResult About()
{
return View();
}
public ActionResult registrationView()
{
// get back my data
string data = ViewData["myData"] != null ? ViewData["myData"].ToString() : "";
return View();
}
}
And you can actually usethe ViewData value on the html/aspx/ascx after redirect to the registrationView.
For example on the registrationView.aspx:
<div id="myDiv">
my data was: <%= ViewData["myData"] %>
</div>
You could simply in you method parameter list declare the parameters with the name of the controls. For example:
The control here has an id "qly"
<input type="text" name="qly" id="qly" />
Define your method parameter list as following:
public ActionResult YourMethod(string qly)
{
//simply pass your qly to another view using ViewData, TempData, or ViewBag, and use it in the desired view
}
You should use TempData which was made exactly for it, to persist values between actions.
This example is from MSDN (link above):
public ActionResult InsertCustomer(string firstName, string lastName)
{
// Check for input errors.
if (String.IsNullOrEmpty(firstName) ||
String.IsNullOrEmpty(lastName))
{
InsertError error = new InsertError();
error.ErrorMessage = "Both names are required.";
error.OriginalFirstName = firstName;
error.OriginalLastName = lastName;
TempData["error"] = error; // sending data to the other action
return RedirectToAction("NewCustomer");
}
// No errors
// ...
return View();
}
And to send data to the view you can use the model or the ViewBag.

MVC3 RemoteAttribute and muliple submit buttons

I have discovered what appears to be a bug using MVC 3 with the RemoteAttibute and the ActionNameSelectorAttribute.
I have implemented a solution to support multiple submit buttons on the same view similar to this post: http://blog.ashmind.com/2010/03/15/multiple-submit-buttons-with-asp-net-mvc-final-solution/
The solution works however, when I introduce the RemoteAttribute in my model, the controllerContext.RequestContext.HttpContext.Request no longer contains any of my submit buttons which causes the the "multi-submit-button" solution to fail.
Has anyone else experienced this scenario?
I know this is not a direct answer to your question, but I would propose an alternative solution to the multiple submit-buttons using clientside JQuery and markup instead:
Javascript
<script type="text/javascript">
$(document).ready(function () {
$("input[type=submit][data-action]").click(function (e) {
var $this = $(this);
var form = $this.parents("form");
var action = $this.attr('data-action');
var controller = $this.attr('data-controller');
form.attr('action', "/" + controller + "/" + action);
form.submit();
e.preventDefault();
});
});
</script>
Html
#using (Html.BeginForm())
{
<input type="text" name="name" id="name" />
<input type="submit" value="Save draft" data-action="SaveDraft" data-controller="Home" />
<input type="submit" value="Publish" data-action="Publish" data-controller="Home" />
}
It might not be as elegant as a code-solution, but it offers somewhat less hassle in that the only thing that actually changes is the action-attribute of the form when a submitbutton is clicked.
Basically what it does is that whenever a submit-button with the attribute data-action set is clicked, it replaces its parent forms action-attribute with a combination of the attributes data-controller and data-action on the clicked button, and then fires the submit-event of the form.
Of course, this particular example is poorly generic and it will always create /Controller/Action url, but this could easily be extended with some more logic in the click-action.
Just a tip :)
i'm not sure that its a bug in mvc 3 as it's not something that you were expecting. the RemoteAttribute causes javascript to intercept and validate the form with an ajax post. to do that, the form post is probably canceled, and when the validation is complete, the form's submit event is probably called directly, rather than using the actual button clicked. i can see where that would be problematic in your scenario, but it makes sense. my suggestion, either don't use the RemoteAttributeand validate things yourself, or don't have multiple form actions.
The problem manifests itself when the RemoteAttribute is used on a model in a view where mutliple submit buttons are used. Regardless of what "multi-button" solution you use, the POST no longer contains any submit inputs.
I managed to solve the problem with a few tweeks to the ActionMethodSelectorAttribute and the addition of a hidden view field and some javascript to help wire up the pieces.
ViewModel
public class NomineeViewModel
{
[Remote("UserAlreadyRegistered", "Nominee", AdditionalFields="Version", ErrorMessage="This Username is already registered with the agency.")]
public string UserName { get; set; }
public int Version {get; set;}
public string SubmitButtonName{ get; set; }
}
ActionMethodSelectorAttribute
public class OnlyIfPostedFromButtonAttribute : ActionMethodSelectorAttribute
{
public String SubmitButton { get; set; }
public String ViewModelSubmitButton { get; set; }
public override Boolean IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
var buttonName = controllerContext.HttpContext.Request[SubmitButton];
if (buttonName == null)
{
//This is neccessary to support the RemoteAttribute that appears to intercepted the form post
//and removes the submit button from the Request (normally detected in the code above)
var viewModelSubmitButton = controllerContext.HttpContext.Request[ViewModelSubmitButton];
if ((viewModelSubmitButton == null) || (viewModelSubmitButton != SubmitButton))
return false;
}
// Modify the requested action to the name of the method the attribute is attached to
controllerContext.RouteData.Values["action"] = methodInfo.Name;
return true;
}
}
View
<script type="text/javascript" language="javascript">
$(function () {
$("input[type=submit][data-action]").click(function (e) {
var action = $(this).attr('data-action');
$("#SubmitButtonName").val(action);
});
});
</script>
<% using (Html.BeginForm())
{%>
<p>
<%= Html.LabelFor(m => m.UserName)%>
<%= Html.DisplayFor(m => m.UserName)%>
</p>
<input type="submit" name="editNominee" value="Edit" data-action="editNominee" />
<input type="submit" name="sendActivationEmail" value="SendActivationEmail" data-action="sendActivationEmail" />
<%=Html.HiddenFor(m=>m.SubmitButtonName) %>
<% } %>
Controller
[AcceptVerbs(HttpVerbs.Post)]
[ActionName("Details")]
[OnlyIfPostedFromButton(SubmitButton = "editNominee", ViewModelSubmitButton = "SubmitButtonName")]
public ActionResult DetailsEditNominee(NomineeViewModel nom)
{
return RedirectToAction("Edit", "Nominee", new { id = nom.UserName });
}
[AcceptVerbs(HttpVerbs.Post)]
[ActionName("Details")]
[OnlyIfPostedFromButton(SubmitButton = "sendActivationEmail", ViewModelSubmitButton = "SubmitButtonName")]
public ActionResult DetailsSendActivationEmail(NomineeViewModel nom)
{
return RedirectToAction("SendActivationEmail", "Nominee", new { id = nom.UserName });
}
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public ActionResult UserAlreadyRegistered(string UserName, int Version)
{
//Only validate this property for new records (i.e. Version != zero)
return Version != 0 ? Json(true, JsonRequestBehavior.AllowGet)
: Json(! nomineeService.UserNameAlreadyRegistered(CurrentLogonDetails.TaxAgentId, UserName), JsonRequestBehavior.AllowGet);
}
I encountered the same issue.
I also attached an on submit event to prepare the form before submit. Interestingly, when I insert a break point in the on submit function, and then continue, the problem has disappeared.
I ended up with an Ajax form by removing the Remote attribute and validate the field using the ModelState.

Resources