I am creating a site in which I utilize partial views to display various bits of data about a single Model. Here is a bit of the HTML. (Note, all of these are contained within a single form and the Index page that these partials are rendered in is strongly typed to the main model. The main model contains various lists of data.)
<div id="tab1"><% Html.RenderPartial("Tab1", Model); %></div>
<div id="tab2"><% Html.RenderPartial("Tab2", Model.AnItemList1.FirstOrDefault<AnItemList1>()); %></div>
<div id="tab3"><% Html.RenderPartial("Tab3", Model.AnItemList2.FirstOrDefault()); %></div>
Here is ONE of the partial views headers (for 'tab2'):
<%# Language="C#" Inherits="System.Web.Mvc.ViewUserControl<AnItem1>" %>
The pages display correctly. The issue is that, when I enter data into the various parts of the partial pages and then submit the entire form (via POST), the data is not making it back to my data store (MSSQL) - but this only happens for any of the list items (that are contained within the Model). The first partial page does properly have its data set within the data store.
What am I doing wrong here? Should I only be passing the model to Html.RenderPartial and then get the specific model I need on the partial page? Should I pass the entire list and then get the first (right now, I only care about the first item in the list - that will EVENTUALLY change, but not any time soon).
Suggestions or thoughts appreciated.
Update: Here is how I accessing the properties on the partial views.
<div class="data-group">
<%: Html.CheckBoxFor(model => model.Property1) %>
<%: Html.LabelFor(model => model.Property1) %>
</div>
Update 2: Per request...
Controller Action (ScenarioController):
public ActionResult Index(int id = 0)
{
if (id == 0)
{
SavedScenario scenario = new SavedScenario();
scenario.AnItemList1.Add(new AnItem1());
scenario.AnItemList2.Add(new AnItem2());
return View("Index", scenario);
}
else
{
SavedScenario scenario = repository.GetScenario(id);
if (scenario == null)
return View("NotFound");
else
return View("Index", scenario);
}
}
[HttpPost]
public ActionResult Index(SavedScenario scenario)
{
if (ModelState.IsValid && TryUpdateModel(scenario, "SaveScenario"))
{
repository.Add(scenario);
repository.Save();
}
return View(scenario);
}
Rendered HTML (I can only include parts of it - this is a small sample of what is in the form):
<form action="/Scenario" id="form0" method="post">
<!-- This is the one that works - the basic Scenario. Top level. -->
<fieldset>
<legend>Scenario Information</legend>
<div class="data-group">
<div class="editor-label">
<label for="ScenarioName">Scenario Name</label>
</div>
<div class="option1">
<input class="wide" id="ScenarioName" name="ScenarioName" type="text" value="" />
</div>
<div class="validation">
<div><span class="field-validation-valid" id="ScenarioName_validationMessage"></span></div>
</div>
</div>
</fieldset>
<!-- This does not work or get submitted (as far as I can tell). -->
<div id="tab2">
<fieldset>
<legend>Tab2</legend>
<div class="data-group">
<input id="Property1" name="Property1" type="checkbox" value="true" /><input name="Property1" type="hidden" value="false" />
<label for="Property1" />
</div>
</div>
</fieldset>
</form>
My apologies for having to keep this so generic.
Hard to guess from this much code. However you should make sure that all properties of your models have the same prefix when they are posted back to the server
Edit: form field names should match property names of your model to correctly bind all values. You have two fields with the same name that you can bind in following way
[HttpPost]
public ActionResult Index(SavedScenario scenario, List<bool> Property1)
{
// here you can do with values coming in property1
if (ModelState.IsValid && TryUpdateModel(scenario, "SaveScenario"))
{
repository.Add(scenario);
repository.Save();
}
return View(scenario);
}
It might be issue with naming the fields on your partial forms. Try naming the fields on your partial views by prefixing it with the name of the Model passed into it...like 'AnItemList1.name' instead of just 'name'..I am just guessing here though...but that's what I did sometimes to fix the problem when I was getting values as null..
Related
I'm iterating my Model.Payments collection (which is an public IEnumerable<Payments> Payments { get; set; }):
#using (Html.BeginForm())
{
<div class="payments">
#foreach (var payment in Model.Payments)
{
Html.RenderPartial("_Payment", payment);
}
</div>
<input type="submit" value="Aggiorna" />
}
And this is my _Payment partial:
#model MyProject.Models.Payments
<div class="payment-row">
<span>ActivityID:</span> #Html.TextBoxFor(x => x.ActivityID)
<span>PaymentType:</span> #Html.TextBoxFor(x => x.PaymentType)
<span>Amount:</span> #Html.TextBoxFor(x => x.Amount)
</div>
But it doesn't create a proper HTML. Name/ID are the same, so once I postback, I can't retrieve data.
Where am I wrong?
The correct approach is to use the EditorFor() method, which will correctly prefix your inputs with the collection indexer
Rename you partial view to Payments.cshtml (to match the name of the class), and move it to the /Views/Shared/EditorTemplates (or /Views/YourControllerName/EditorTempatesFolder)
Then you view becomes
#using (Html.BeginForm())
{
<div class="payments">
#Html.EditorFor(m => m.Payments)
</div>
<input type="submit" value="Aggiorna" />
}
The EditorFor() method generates the correct html for each item in the collection, and will generate inputs such as <input name="Payments[0].ActivityID" ... /> rather than <input name="ActivityID" ... /> which you are currently generating.
As a side note, you should consider using #Html.LabelFor() to generate a <label> associated with your form controls, rather than using a <span>.
I want two CheckBoxList an index view, those
CheckBoxList dynamically bind from two different tables. One is Sports
and another is Country.
Basically i try through EditorTemplates, but it not working with two
models. i face problem to use two model in a single view.
This is my Index Method in Controller
SampleDBContext db = new SampleDBContext();
public ActionResult Index()
{
ViewData["Sports"] = db.Sports.ToList();
ViewData["Country"] = db.Countries.ToList();
return View(ViewData["Sports"]);// I am confused and i don't know what to write there we can call both table data.
}
Template View for Sports
#model MVCDEMO.Models.Sports
#Html.HiddenFor(x => x.s_Id)
#Html.CheckBoxFor(x => (bool)x.is_selected)
#Html.DisplayFor( x => x.s_Name)
Template View for Country
#model MVCDEMO.Models.Country
#Html.HiddenFor(x => x.c_Id)
#Html.CheckBoxFor(x => (bool)x.is_selected)
#Html.DisplayFor( x => x.c_Name)
Index View
<div class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">
Select Sports
</label>
<div class="col-md-3">
#Html.EditorForModel()//what to write it recognize Sports template
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">
Select Country
</label>
<div class="col-md-3">
#Html.EditorForModel()//what to write it recognize Country template
</div>
</div>
</div>
If i work for single Model it work perfectly.
I would personaly use a strongly typed view model having Sports and Countries as properties, instead of using ViewData:
public class IndexPageViewModel
{
public IEnumerable<Sports> Sports { get; set; }
public IEnumerable<Country> Countries { get; set; }
}
Creating two partial views, one for each class (Sport and Country), would allow you to use the #Html.EditorForModel() helper. Reusing the partial views would also be an added benefit, but this obviously depends on the specific application.
Please note that the 'EditorForModel' helper will render an editor for each property of the model. If you need to have a different kind of editor, for example a dropdown menu, I'm not sure EditorForModel should be used.
In short:
When using Backbone and Underscore templates, what's the best way to ensure that the data in a form is formatted in the exact same way when POSTed to the server as it was when it was initially fetched?
Longer question:
I'm currently using Backbone’s fetch() to retrieve some data from the server as JSON. On success I'm taking that JSON and using the data in an Underscore template like so:
<div class="module-content">
<form>
<div class="customer-primary">
<% if (ParentCompany) { %>
<div class="row">
<div class="label">Parent Company</div>
<div class="value">
<div class="current-value"><%= ParentCompany %></div>
<div class="editable-value"><input name="ParentCompany" value="<%= ParentCompany %>"></div>
</div>
</div>
<% } %>
<% if (Title) { %>
<div class="row">
<div class="label">Title</div>
<div class="value">
<div class="current-value"><%= Title %></div>
<div class="editable-value"><input name="Title" value="<%= Title %>"></div>
</div>
</div>
<% } %>
…
</div>
</form>
</div>
The JSON has a number of children with multiple entries, like this:
{
"UserID":"12345",
"FirstName":"Brandon",
"Ship": {
"Address1":"33 One Two Ave",
"Address2":"#23D",
"Address3":"",
"City":"New York",
"State":"NY",
"Country":"United States",
"Zip":"10023"
},
"Phones": [
{
"Kind":"Tel",
"Number":"512-123-4567"
},
{
"Kind":"Fax",
"Number":"512-123-4567"
}
]
}
How can I ensure that I build the form out in such a way that it returns an object that's formatted in the same way for easy DB updates?
Please let me know if you need more info!
If I understand your question, you're trying to make sure the JSON data structure matches what the server expects when you're sending data. (And coincidentally, that it's in the same structure that you received from the server.)
What you want to do is override the model's toJSON function so your data is serialized as expected. Then, when it gets persisted by Backbone.sync, the proper data structure will be sent to the remote API.
Take a look at these:
Saving Backbone model and collection to JSON string
backbone.js: overwritting toJSON
I think the best you can do is to validate your model. and make the fields that you need to be sent required, if you need all of them ,then validate your entire model.
This plugin is a good option for this task.
https://github.com/fantactuka/backbone-validator
I have a main view that renders two partial views. The main view encompasses both of the partial views within a form. Each of the partial views also contain forms. All 3 views share the same viewmodel. What I want to do is encapsulate the data from all views with the main view, and run specific Controller action results with the partial views.
I want to know if this is even possible. When debugging I see that my content always posts to the HTTPPost of the Main views form. I have submit buttons for each of the forms accordingly. Sorry for the code post, its coming out all split up.
Main View:
#using (Html.BeginForm("Main", "Registration", FormMethod.Post,
new { #class="mainform" }))
{
<form>
<fieldset>
<div id ="option1" class="conglomerate">
#Html.Partial("_GetBusiness")
</div>
<div id ="option2" class="dealership">
#Html.Partial("_GetLocation")
</div>
<button type="submit" value="Create" class="buttonBlue" id="">
<span>Create a new dealer</span>
</button>
</fieldset>
</form>
Partial 1
#using (Html.BeginForm("CreateBusiness", "Business", FormMethod.Post,
new { #class="buisinessform" }))
{
<form>
<div class="editor-field">
#Html.DropDownListFor(m =>m.BusinessId, new SelectList(Model.Businesses,
"BusinessId", "BusinessName"), "")
</div>
<label>Your company not listed? Register yours below:</label>
<div class="editor-label">
#Html.LabelFor(model => model.BusinessName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.BusinessName)
#Html.ValidationMessageFor(model => model.BusinessName)
</div>
<button type="Button" value="" class="buttonBlue"id="TestSubmit">
<span>Add Dealer</span>
</button>
<div class ="confirm">
<button type="submit" value="Create" class="buttonBlue" id="">
<span>Click here to confirm dealer addition</span>
</button>
</div>
</form>
}
As Dave mentions, It is not valid HTML to nest forms. It's not just HTML5, but any version of HTML.
It might work in some browsers, in certain circumstances, but it is never valid. And you can never depend on what will happen even if it does seem to work. Your best course of action is to use multiple non-nested forms on a page.
Can you explain why you think you need nested forms?
No, you cannot have nested forms. Sorry.
See HTML5 guidelines
"Flow content, but with no form element descendants"
In my view i have two partial views (Search,webgrid). When i click the update button in the search , the values filtered are not binding in the webgrid ? How can i do this?
You could try something like this. Hope I understood your question correctly.
search partial:
...
#using(Ajax.BeginForm("Search", new AjaxOptions(){UpdateTargetId = "SearchResults",
HttpMethod = "post" InsertionMode=InsertionMode.Replace})){
<input id="searchString" type="text" value="Search for this ..." />
<input type="submit" value="Search" />
}
...
controller:
[HttpPost]
public PartialViewResult Search(string searchString){
IList<Results> results = _service.Search(searchString);
return new PartialView("Webgrid", results)
}
webgrid partial:
#Model IList<Result>
<div id="SearchResults">
// Display Results
</div>
Didn't compile the code. Hope it is almost compileable.