MVC how can i post a form without using a model - forms

I would like to know how i could sumbit a form in mvc 4 without using a model binding to the view.
can some one please demontrate how? and how can i use that form in the controller?

It is very easy to use a form without any sort of Model binding.
Simple set up your for using either #using(Html.BeginForm()){ ... } or plain html.
<form id="myForm" action="/ControllerName/ActionName" method="Post">
<input type="text" name="foo" value="FOOOO" />
<input type="text" name="bar" value="Baaaar" />
<button type="submit">Submit</button>
</form>
When you post this to the ActionResult, your action result just needs to be set up to accept a string value named foo and one named bar
[HttpPost]
public ActionResult ActionName(string foo, string bar){
// your code here
return View();
}

Related

Checkbox input remains false on form submit

I am trying to post a form and even though all the inputs map their value accordingly in the receiving controller-method , the bool-s of checkbox-es remain false.
What am i doing wrong ?
POCO
class MyPoco
{
public string User{get;set;}
public bool Require {get;set;}
}
Form
<form id="createForm" method="post" action="[some url]">
<input type="checkbox" id="require" name="Require" />
<input type="text" id="user" name="User"/>
</form>
Controller (method)
[HttpPost]
[Route("[some url]")]
public async Task<long> CreateAsync(MyPoco request)
{
}
Why in my case above does request.Require is always false.I have mapped them correctly (the name attribute).
The reason is that you forget to set value of checkbox:
<input type="checkbox" id="require" name="Require" value="true" />
If a checkbox is checked, then the postback values will contain a key-value pair of the form [InputName]=[InputValue]
If a checkbox is not checked, then the posted form contains no reference to the checkbox at all.
I see you are missing asp-for attribute for your checkbox input. Instead of name="Require", use asp-for="Require" as follows:
#model MyPoco
<input asp-for="Require" type="checkbox" id="require" />
If you don't want to use asp-for attribute then you have to use jQuery as follows:
$(document).on('change','#require',function() {
if ($(this).is(':checked')) {
$(this).val(true)
} else {
$(this).val(false)
}
});

fatfree framework, repopulate fields after unsuccessful validation

I have GET route which shows the contact form, and POST route when user submits the form, then in my controller method I do some validation tests on data being submitted.. how would I now send user back to form if data is not valid, with entered data being re-populated in form fields?
I know I can use isset(#POST.fieldname) in my template, but what's the right way of
sending entered data back to that view, and how to redirect user back to the
form? Is the f3->reroute method right way of doing that?
I think you can take as a rule to include input data inside your form views. This way, any form view will be easily reusable with any source of data.
For example:
Your form view:
<form action="" method="post">
<input type="text" name="email" value="{{ ##input.email }}"/>
<input type="text" name="message" value="{{ ##input.message }}"/>
<button type="submit">Submit form</button>
</form>
Your controller class:
class myController {
function get($f3) {
$this->renderForm();
}
function post($f3) {
$post=$f3->clean($_POST);
//validate form data here
if ($form_validated) {//valid form data
} else //invalid form data
$this->renderForm($post);
}
protected function renderForm($input=array()) {
$tpl=Template::instance();
//variant 1:
echo $tpl->render('form.html','text/html',array('input'=>$input))
// or variant 2:
Base::instance()->set('input',$input);
echo $tpl->render('form.html');
}
}
In some other contexts, you can feed a form view with data coming from a db mapper (for example when editing an entry from a back-office): $this->renderForm($mapper->cast())

MVC4 Pass Model from View to Controller

//Model
public class Car
{
string name{get;set;}
double speed {get;set;}
//etc.
}
Basic model
//Controller
public ActionResult ModifyCar(Car c)
{
c = GetAdditionalData(c.name, c.speed);
return View(c);
}
So I'm making call to outside service to get additional data for car.
Below is the form which I'm really confused on. I am just going to write this in HTML.
But from here I'd like to take a basic empty model.. populate it then send to the controller for additional data.
//View
#model Car
<form id="carform" method="post" action="/Car/ModifyCar"> //Guessing
<input id="carName" /> //Somehow bind with #model.name
<input id="carSpeed" /> //Somehow bind with #model.speed
<input type="submit" /> //Somehow send the model to the controller
</form>
Sorry I'm not really good at the View part at all but I hope you can see where I was going here.
Also, I'm doing validation that requires a form id.. I noticed that there is no form id when using HTML Helper to make the form. Thats going to break my CSS I wrote.
Any help would be greatly appreciated.
Thanks
Try this :
#model Car
<form id="carform" method="post" action="/Car/ModifyCar"> //Guessing
<input id="carName" name="carName" value=#Model.name /> //Somehow bind with #model.name
<input id="carSpeed" name="carSpeed" value=#Model.speed /> //Somehow bind with #model.speed
<input type="submit" value="Submit" /> //Somehow send the model to the controller
</form>
when your form will submit it will go to ModifyCar action in Car
Controller.
But as you has mentioned in your question that we cannot give id in html helper ,it is wrong we can for ex:
#using(Html.BeginForm("ModifyCar","Car",FormMethod.Post,new{ id="carform" }))
the above BeginForm() will render same html as:
<form id="carform" method="post" action="/Car/ModifyCar">

Dynamically adding form elements with jQuery and Zend_Form

I have a form in which people shall be able to add the same portion of elements with a plus-button, so that something like this is produced:
<div id="person-1" class="person">
<input type="text" name="name-1" id="name-1" />
<input type="text" name="age-1" id="age-1" />
</div>
<!-- as of here, it's JS created -->
<div id="person-2" class="person">
<input type="text" name="name-2" id="name-2" />
<input type="text" name="age-2" id="age-2" />
</div>
<div id="person-3" class="person">
<input type="text" name="name-3" id="name-3" />
<input type="text" name="age-3" id="age-3" />
</div>
I already managed to write jquery-code that allows me to add the same elements once again with a new id (name-1, age-1, name-2, age-2, name-3, age-3, …).
Of course, Zend_Form does not know about name-2 and name-3, so it just drops them when the form contains an error and is displayed again. Neither can I access the value of name-2 with $form->getValue('name-2'). I have to go over raw $this->getRequest()->getPost().
Is there a better method I can use to combine Zend_Form and javascript-based added form elements (of same type like an hardcoded element).
Caveat: In the real problem, it’s select and not input. Found out this could make a difference (with ->setIsArray(true)), but using select would blow up the example code.
What you could do is create a subform container inside your main form and add an X amount of subforms to that container.
For example:
class My_Form extends Zend_Form
{
private $_numPersons = 1;
public function setNumPersons($numPersons)
{
$this->_numPersons = (int) $numPersons;
}
public function init()
{
$container = new Zend_Form_SubForm();
$this->addSubForm($container, 'persons');
for($index = 0; $index < $this->_numPersons; $index++) {
$personForm = new My_PersonForm();
$container->addSubForm($personForm, $index+1);
}
}
}
When rendered, the input fields will have names like persons[1][name]. Note the $index+1, Zend_Form does not allow a form to be named '0'.
Ofcourse, you should only use this method if the amount of person subforms is limited.
Another strategy would be to override the isValid method and use a single My_PersonForm form to validate all the person data.
Sidenote; the above code will only work when you define the numPersons as part of the options set, when creating the form instance. E.g.;
$form = new My_Form(array('numPersons' => 10));

ASP .Net MVC 2 custom Helper Grid not posting Model to controller action

I've created a custom helper that renders a grid and receives the strongly typed view's model as a parameter.
Basically my view looks like this:
<% using (Html.BeginForm("UpdateValues", "Home", FormMethod.Post)) { %>
<%= Html.MyGrid(Model)%>
<input type="submit" value="Update Values" />
<%} %>
But when I click on the submit button, all the values on the model are null.
This is what the controller looks like:
[HttpPost]
public string UpdateValues(AssignmentResultsVm assignmentResults)
{
//..... do something
}
How can I make this work?
Thanks in advance.
You need to make sure that the items are arranged in your grid so that the default model binder can map the data map to your view model class.
This is done by index the name property of the data your are binding like this:
<form method="post" action="/Home/Create">
<input type="text" name="[0].Title" value="Curious George" />
<input type="text" name="[0].Author" value="H.A. Rey" />
<input type="text" name="[1].Title" value="Code Complete" />
<input type="text" name="[1].Author" value="Steve McConnell" />
<input type="submit" />
</form>
You can have this done for you by the EditorTemplates feature of asp.net mvc which is exemplified in this article.