I am new to mvc i am trying to pass model into controller from view
This is my view
My Control
but while debugging im getting all null values
i am using view model
where i am doing mistake
Help me
thanks
You cannot use an ActionLink to post a form. Have a look at this post
#model YourViewModel
#using(Html.BeginForm())
{
Model NAme : #Html.TextBoxFor(s=>s.Name)
<input type="submit" value="Post to server" />
}
You seem to use an "ActionLink" to call the "AddUser2" method controller. An ActionLink generates a basic link which redirects to the controller passed in parameter.
You need to post the form (to send values typed by the user to the controller), not redirect.
To post the form, use the following html tag (instead of the ActionLink) :
<input type="submit" value="ok" />
This code generate a button, which will send your form when user will click on it.
Related
In Asp.net MVC, Is it possible to have a form post to two different actions based on model value when clicked on the same button?
Ex. - I want to add a new customer or update an existing customer on click of the same button "Save". Can the form be posted to two different action methods based on the customer's id value.
if the customer id value = 0 , then post it to "Create" acction method , if the customer id value is already present (not equal to 0), then post the form to "Update" action method?
Is this possible in asp.net mvc?
No You cant call multiple action on submit with fairly way,
You need to add hiddenfield for id
<input type="hidden" name="id" value="#model.Id" />
When you submit the form the value will be retrieve from model
And check the hidden field value is 0 or not
If 0 than the entity needs to create else it is for update
public ActionResult Save(Customer customer){
if(customer.id > 0){
// Update Entity
}
else{
// Create Entity
}
}
Yes. It is possible. There are multiple ways to do it.
1) You can conditionally set the form action attribute value based on your view model property value.
<form method="post" action="#(Model.Id==0?Url.Action("Create","Home")
:Url.Action("Update","Home"))">
<input type="text" name="FirstName" />
<button type="submit">Save</button>
</form>
2) Another option is, you can add html5 formaction to your submit button and the value of that attribute could be the url to create or update action method based on your Id property value.
#using (Html.BeginForm("Create", "Home"))
{
<input type="text" name="FirstName" />
<button type="submit"
formaction="#(Model.Id==0?Url.Action("Create","Home")
:Url.Action("Update","Home"))">Save</button>
}
When you specify the formaction attribute on a submit button, it will overrides the parent form's action attribute value.
3) Another option is to hijack the form submit event in javascript, prevent the default behavior (stopping the form submit) and then update the form's action attribute value to /create or /update and trigger form submit using javascript. You can keep the Id property value in a hidden field inside the form and read the value of that and use that to determine what should be the url for the form's action attribute value.
Assuming you have a hidden element for the Id of type int property in your page
#model YourViewModel
#using (Html.BeginForm("Create", "Home",FormMethod.Post,new {id="yourFormId"}))
{
#Html.TextBoxFor(a=>a.FirstName)
<button type="submit">Save</button>
#Html.HiddenFor(a=>a.Id)
}
and the javascript to hijack the form submit and update the form's action attribute value would be like
$(function () {
$("#yourFormId").submit(function(e) {
e.preventDefault(); // stop the normal form submit
var id=parseInt($("#Id").val());
var url=$(this).attr("action");
if(id===0)
{
url='/Home/Update'; // Use the Url.Action to be safe to generate this
}
// read the data attribute and update the forms action and do a submit
$(this).closest("form").attr('action', url).submit();
});
});
4) Another option is always submitting the form to Update or Create action and inside that method, based on the the Id property value, execute the code for Update or Create as needed.
Yes. This for the View case:
#mode MyModel
#{
string action = Model.Id == 0 ? "Create" : "Edit"
}
#using (Html.BeginForm(action, "MyController"))
{
// if Edit need Id
if(action == "Edit")
{
#Html.HiddenFor(model=> model.Id)
}
#Html.TextBoxFor(model >= model.Name);
<input type="submit" value="Save">
}
In my ASP.NET MVC (5.2) project, I have a page called register.cshtml. It doesn't include any forms or anything, just plain divs.
Inside one of the divs, I'm rendering a partial:
#Html.Partial("~/Views/Users/_x.cshtml").
Inside _x.cshtml I have a form:
#using (Html.BeginForm("/users/x"))
{
...
}
When I go to my register page, I expect my form to be rendered as:
<form action="/users/x" method="post"> ... </form>
But instead, I'm getting this:
<form action="/users/register?Length=23" method="post" novalidate="novalidate"> ... </form>
What is length=23, why is there a novalidate attribute added, and why is it posting to an incorrect path?
Why is my form not rendering properly?
If your wanting to post to a method named x in usersController, then it needs to be
#using (Html.BeginForm("x", "users"))
{
....
}
Note that your currently using the overload that accepts object routeValues and because its a string, the method generated a route value for Length because that's the only property of string (the /users/register is because that the method that generated the main view)
From your code
Html.BeginForm("/users/x")
i understand that users your controller and x is a method. So you can do in this way-
#using (Html.BeginForm("x", "users", FormMethod.Post, new { id = "YourFormID"}))
{
}
#using (Html.BeginForm("action", "controller",new { QueryString = 1}, FormMethod.Post, null))
{
}
Note : its due to passing wrong parameter in beginform constructor .
and in ur VIEW
#Html.Partial("~/Views/Shared/_x.cshtml")
I have an AJAX.BeginForm() form and I want to submit an Html post as the final post. Here's my form
#using (Ajax.BeginForm("createSet", "Workout",
new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "divs",
HttpMethod = "POST"}, new { id = "myForm" }))
{
<div id="divs">
#Html.Partial("WorkoutSet", Session["WorkoutSetList"])
</div>
#Html.ActionLink("Submit", "SavePlan", "Workout", new { type = "submit" });
//<input type="submit" value="Submit" id="submit" name="command" />
<input type="submit" value="Create Set" name="command" />
}
Basically my "create set" button is used a lot for ajax calls which is working fine. I'm able to bind the model rendered from the partial view and update my model to session on every ajax call.
For my final step, I want to submit the whole form to the SavePlan Action along with the model values and then redirect to home page after that.
Problems faced:
First I tried the Ajax Submit button(the code commented out), a script redirects it to the SavePlan along with the model values rendered from partialview. Only problem is I could not redirect to HomePage and I've read that redirection cannot be done on an ajax call.
Second, I've tried the #Html.ActionLink which does goes to the SavePlan action and then proceeds to redirect to HomePage, BUT the model values were never passed. I've tried FormCollection but the values don't get passed either.
Please provide some advise on how to solve this? I've already spent 2 days on it and I'm tearing myself on it.
To recap:
Trying the Ajax way allows me to pass the model values but does not redirect to home page
Trying the Html way doesn't allow me to pass the model values but does redirect to home page.
You can redirect from an ajax POST - in your controller, you need to return a window.location javascript snippet:
return JavaScript(string.format("window.location = '{0}'", Url.Action("Index")));
There is an article here: Breaking out of an AJAX POST
My one view page I passed in a model through the controller, so I can write:
#Html.DisplayFor(m => m.FirstName) which displays the First Name of the model. When I try to submit the form on the page using
#using (Html.BeginForm("CreateUser", "Controller", FormMethod.Post, new { UserViewModel = Model }))
and I take a look at my model in
[HttpPost]
public virtual ActionResult CreateUser(UserViewModel model)
{
//model.FirstName is blank
Is there anyway I can make the model.FirstName not blank? by some how passing the model that I originally passed? I could set a bunch of hidden remarks, though if there is a better way that would be very helpful
EDIT: the DisplayFor is just an example to show the model is accessible. I actually have about 15 fields, and I am going through multiple forms trying to populate the model. Is Hidden the only way? and could I just hide the entire model?
#Html.DisplayFor() creates a simple literal with the value by default (if you're not using a display template), on submit only form elements being submitted to the server.
You can use hidden input.
#Html.HiddenFor(m => m.FirstName)
Which will be something like:
<input type="hidden" value="{the first name}" name="FirstName" id="FirstName" />
I'm using ASP.NET MVC Preview 4 and would like to know how to use the routing engine for form submissions.
For example, I have a route like this:
routes.MapRoute(
"TestController-TestAction",
"TestController.mvc/TestAction/{paramName}",
new { controller = "TestController", action = "TestAction", id = "TestTopic" }
);
And a form declaration that looks like this:
<% using (Html.Form("TestController", "TestAction", FormMethod.Get))
{ %>
<input type="text" name="paramName" />
<input type="submit" />
<% } %>
which renders to:
<form method="get" action="/TestController.mvc/TestAction">
<input type="text" name="paramName" />
<input type="submit" />
</form>
The resulting URL of a form submission is:
localhost/TestController.mvc/TestAction?paramName=value
Is there any way to have this form submission route to the desired URL of:
localhost/TestController.mvc/TestAction/value
The only solutions I can think of are to create a separate action that just checks the request parameters, or to use Javascript.
Solution:
public ActionResult TestAction(string paramName)
{
if (!String.IsNullOrEmpty(Request["paramName"]))
{
return RedirectToAction("TestAction", new { paramName = Request["paramName"]});
}
/* ... */
}
In your route, get rid of the {paramName} part of the URL. It should be:
TestController.mvc/TestAction
As that is the URL you want the request to route to. Your form will then post to that URL.
Posted form values are mapped to parameters of an action method automatically, so don't worry about not having that data passed to your action method.
My understanding is that this is how HTML works. If you do a <form url="foo" method="get"> and post the form, then the form will post foo?
param1=value1&...¶mn=valuen
It has nothing to do with MVC.
Besides, what part of REST does that URL violate? It's not a pretty URL, but by strict definition of REST, it can be RESTful. REST doesn't specify that query parameters have to be in an URL segment. And in this case, those are query parameters.