Posting a form from a partial view - asp.net-mvc

I have a modal which I will be using extensively on many different pages and hence I thought putting it in a partial view was appropriate. Within the modal is a form but I'm just getting a 'can't find action on controller error' whenever I try submit the form.
#using (Html.BeginForm("AddPlayerSignup", "SignupSheet", new {id = Model.Id, slug = Model.Slug}))
{
#Html.DropDownList("Member", Model.SignupSheet.GroupMembers, new {label = "Members"})
#Html.Hidden("SignupSheetId", Model.SignupSheet.Id)
#Html.Hidden("ModalId", Model.ModalId)
#Html.SubmitButton("Add", true, new {#class = "btn btn-primary"})
}
The weird thing is it's not even saying it can't find addplayersignup on signupsheetcontroller, it's saying it cant find list on ladder which is the source of the partial view.
Is posting forms from a partial view not supported or something?

It looks like you forgot to add a form method,...
#using (Html.BeginForm("AddPlayerSignup", "SignupSheet",FormMethod.Post ,new {id = Model.Id, slug = Model.Slug}))
That should do the trick

Related

Second model in same view not posting to controller

With the help of several SO questions, I've figured out how to use two models on the same view, using the tuple form. At the top of my file is this:
#using Project.Models;
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
#model Tuple<Foo, Bar>
}
For the Foo stuff, it uses jQuery like this:
#Html.DisplayFor(tuple => tuple.Item1.ID)
and works fine. However, for my second model, it isn't displaying info, but is a submission form. Currently, this is what I have:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "createFoo", #action = "/api/Foo" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="editor-field">
#Html.TextAreaFor(tuple => tuple.Item2.Text)
#Html.ValidationMessageFor(tuple => tuple.Item2.Text)<br />
</div>
<input type="submit" value="Post Response" />
}
Mind you, this is mostly copy paste from other views since I'm new to MVC and it worked fine with other forms. For my FooController, I have this:
public void Post([FromBody] Foo foo)
{
Foo existingFoo = this.fooRepository.GetFoo(foo.ID);
if (existingFoo != null)
{
// throw error
}
else
{
System.Diagnostics.Debug.WriteLine("MESSAGE POSTING: " + foo.Text);
}
}
When submitting from the view, the received foo isn't null (checked in other tests), but the foo.text is empty. I've tried lots of different inputs and such, but I'm just so unfamiliar with the #Html.* functions and ASP.net-MVC in general that I'm not sure where I could be going wrong.
If you need to see my repository code let me know, but I doubt it'd have an effect on this. Thanks in advance for any help.
There are 2 issues I can see with your code above:
The way the Html helper will output your fields and how that feeds into your api post
Not having your ID in the controller.
1: Outputting a field like this (#Html.TextAreaFor(tuple => tuple.Item2.Text)) will give the field the name "Item2.Text". This is an issue as that is what gets passed on the post. You will get form data with Item2.Text:dfsdsgdfg. This won't match when your API controller tries to bind. So, try outputting the text field with a set name:
#Html.TextArea("Text", #Model.Item2.Text)
2: Your Id field is not in the form... thus it won't be sent. Try using a hidden field:
#Html.Hidden("ID", #Model.Item1.ID)
Also, just a clarification, this (#Html.DisplayFor(tuple => tuple.Item1.ID)) is not jQuery.

Mvc 4 validation summary errors not displaying

I am having trouble displaying validation summary, I only want to display errors in validation summary, not beside the field.
In my view i have,
#Html.ValidationSummary()
#Html.ValidationMessageFor(m =>m.Name)
in my controller i have
ModelState.AddModelError("Name",
"name is required");
Am i not supposed to get a validation error message? at the top?
I don't get what i am missing...
I am also including these script files..
jquery.validate.min.js
jquery.validate.unobtrusive.min.js
Try
#Html.ValidationSummary(false)
so that it will not exclude property errors.
OR
Try the method #xurca linked which is to add the model error with an empty key so it is not tied to a specific property.
ModelState.AddModelError(String.Empty, "name is required");
If you custom named your field like
#Html.TextBoxFor(model => model.Name, new { id = "staffSearchFilterName", value = "", **Name = "staffSearchFilterName"** })
then you have to use
#Html.ValidationMessage("staffSearchFilterName")
If your #Html.ValidationSummary() call is in a Partial view, DON'T pass data into the partial view like this:
#Html.Partial("_YourForm", Model, new ViewDataDictionary { { "Submit", true }})
Instead, add the key value pair to Html.ViewData collection first:
#{
Html.ViewData.Add(new KeyValuePair<string,object>("Submit",true));
}
then call the partial view:
#Html.Partial("_YourForm", Model, Html.ViewData)
this will allow the ModelState to propagate to the partial view properly.

How can I name a form with Html.BeginForm()?

How do I give a name to a form in ASP.NET MVC using Html.BeginForm()? I want only the name, not the action or controller name because I want to post it through Javascript. I think it should be something like Html.BeginForm(id = "frm").
I tried the following:
Html.BeginForm(null,null,new{id="frm",name="frm})
Html.BeginForm(new{#id="frm",#name="frm})
But the above code produces output like this:
<form action="/Main/Index/Id?name=Id" method="post">
Html.BeginForm(null, null, FormMethod.Get, new { name = "frm", id = "frm" })
You'll need to catch the form submit with your JavaScript
Using MVC2, this is what worked for me:
<% using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new {#id = "myForm", #name = "myForm"})) {%>
#HTML.BeginForm("Target-ViewName where you want to post the page","Controller Name",new {#name="Name of the Form", id="ID of the Form"})
{ //form here
}
Taken from this answer: How to pass in ID with Html.BeginForm()?
Can you not just do:
Html.BeginForm(new {#id="Id", #name="Id"});
It can pay to search SO for answers as I've found many things I want to ask have already been encountered.

ASP.NET MVC 2 Html.TextAreaFor not updating on Edit

I have a form that lets the user enter in some text. It will be longer than a few characters so I want to use a TextArea instead of a TextBox.
The Html.TextBoxFor works without issue, and the Html.TextAreaFor works when I create the entry, but does not store the new value when I edit it and shows whatever the value was before I went to edit it upon saving.
On Page:
<div>
<label>Work Performed:</label>
<%: Html.TextAreaFor(model => model.WorkPerformed)%>
<%: Html.ValidationMessageFor(model => model.WorkPerformed) %>
</div>
Code Behind for Create:
maintPerformed.MaintDate = DateTime.Parse(Request.Form["MaintDate"]);
maintPerformed.WorkPerformed = Request.Form["WorkPerformed"];
maintPerformedRepository.Add(maintPerformed);
maintPerformedRepository.Save();
return RedirectToAction("Details", new { id = maintPerformed.ID });
Code Behind for Edit:
maintPerformed.MaintDate = DateTime.Parse(Request.Form["MaintDate"]);
maintPerformed.WorkPerformed = Request.Form["WorkPerformed"];
maintPerformedRepository.Save();
return RedirectToAction("Details", new { id = maintPerformed.ID });
What am I missing on the edit side of things?
In both cases you are redirecting to the Details action. So make sure that maintPerformedRepository.Save() actually does something and most importantly in your Details action look what value is fetched from the data store. I suspect that either the database is not updated or in your Details action you are fetching a wrong value for your model.
Remark: Instead of writing the ugly DateTime.Parse(Request.Form["MaintDate"]); and Request.Form["WorkPerformed"]; pass your view model as argument to your controller action and let the model binder populate it from the request values.

ASP.NET MVC usercontrol create and edit mode setting

I'm using an ASP.NET MVC usercontrol to represent a form for both a "create" mode and an "edit" mode.
The form involves a file upload so looks something like this:
<% using (Html.BeginForm("Create", "News", FormMethod.Post, new { enctype = "multipart/form-data" }))
How can I make it post to the Create action in create mode and Edit action in edit mode?
I'm rendering it in the View like this:
<% Html.RenderPartial("NewsForm"); %>
Simple. Don't specify the action name in your call to Html.BeginForm. By default the same action name is used for POST as for GET (and similarly for controller). So if you just do:
<% using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
...then you get what you want.
A general rule of thumb for ASP.NET MVC is, "If your code is not doing what you want, try removing some of it."
The best way is to take all the fields and put them into a partial view and have the main view (Create/Edit) do the different begin forms.

Resources