Two views 1 Model MVC - asp.net-mvc-4

When using MVC to capture information in a form, can I break up the from in two views but still use a single model, and write to the db at the last form?
For example Account.cs model has name and surname
I want view1 to capture name, view2 to capture surname and when i click submit it must write to the db.

You can use a model on however many views you like. In fact, one of the features of MVC is that it allows you to use the same model and controller action with different views to present the same data in difference way.
However, in this case, you will be responsible for getting the data from the first view into the second view, so the submit action can write both together.

I don't believe it is possible to use a single form across two views. However, you can use two forms for the two views, using a single model. In view1, capture the name and call the following controller action:
public ActionResult(Account model)
{
return View("View2", model");
}
Then, simply use a hidden input to store the information from view1 in the form in view2:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(x => x.Name)
#Html.TextBoxFor(x => x.Surname)
</div>
}

Related

MVC 4 Partial view with different model called with AJAX

I'm trying to solve a problem. I am new to MVC and trying to understand how the models work. I get the main page and main model stuff and that if you want to show a partial view the data you show must be part of the main model. This makes the main model pretty large and doesn't that require me to submit the entire model to get the partial view? In any case, let's say I have a list of things and one column is a link. This link calls an AJAX method to get more data and display in a jQuery dialog - my goal. So I would have a call like this:
function showDetails(id) {
$("#divShowDetails").load('#(Url.Action("GetDetails", "Home", null, Request.Url.Scheme))?Id= ' + id);
}
My view is like "_DetailsView.cshtml", defined as a partial view. Does this page need to define the model in the main page or can it be a different model or no model at all? Can I return a ViewData from the controller method, pop open the dialog and fill it with data?
Should the controller method return a PartialViewResult or just an ActionResult? Let's say the details view are details of a part number or something and I want to show a bunch of data elements for the part. Does this have to me a model? I am confused and any help would be greatly appreciated.
Thanks guys. Do you still use the common:
[HttpGet]
public PartialViewResult SelectedItem (string itemId)
{
// gather data for the item
return PartialView(itemModel);
}
And you are saying that the itemModel does not have to be part of the item list model?

Render a JBuilder view in html view

I've created a json view with JBuilder. But I want to preload this into a data object, so Backbone has access to the data early on without fetching for it.
How can I render the list.json.jbuilder view into my list.html.erb view?
Normally without jbuilder, I'd do something like this:
<div data-list="<%= #contents.to_json %>"></div>
render, when called from within a view, returns a string rendering of the passed template or partial; you can embed that string into your view as you like. Note though that:
You have to append your template name with the type suffix/extension. If you don't, Rails may get confused about which template file you're calling; ie: it might choose list.html.erb instead of list.json.jbuilder. If you're making this call from list.html.erb, trying to render list.html.erb results in infinite recursion and a SystemStackError. Using the :format option for render doesn't appear to work.
You have to specify the qualified path to the template; it won't find the right template for "list.json" just because list.json.jbuilder resides in the same directory as list.html.erb.
You need to pass the output of the render call through raw; otherwise, it will get escaped when it gets embedded into the view.
So, for your example, you might write this, assuming your templates were in /app/views/foo:
<div data-list="<%= raw render(:template => "foo/list.json", :locals => { :contents => #contents }) %>"></div>

ExtJS grid 'reset'

I'm on ExtJS 4 and using an MVC approach. I've created a simple grid view class, and have added a componentquery type 'ref' to that view in my controller. Within the initial grid view itself I set several columns to be hidden and some to be visible by default. The rendering of the grid with those settings is all working fine.
Then I have a button that, when clicked and based on some other conditions, will make some of the initially hidden grid columns visible. This works as well.
But what I need is a way to later 'reset' the grid to its initial view (with the correct columns hidden/visible, as they were initially).
I've tried various permutations of the following with no effect:
var theGrid = this.getTheGrid();
theGrid.reconfigure(store, theGrid.initialConfig.columns);
theGrid.getView().refresh();
I suppose I could loop through every column and reset its 'hidden' state, but would think there's a way to just 'reset' back to what's set in the class? Advice?
SOLUTION UPDATE
Appreciate the pointer from tuespetre. For anyone coming along in the future looking for specifics, here is what was needed (at least for my implementation):
Within the view, moved the column defs into a variable
Within the view, columns ref within the class becomes:
columns: myColumns,
Within the view, the following function created within the class:
resetGrid: function(){
this.reconfigure(null, myColumns);
},
Within the controller:
var theGrid = this.getTheGrid();
theGrid.resetGrid();
You will just need to create a function on your view class to encapsulate that functionality.

Yii: Receiving multiple records for a single model from view in POST method: To save Parent Child data

I am in a situation where I have more than 4 child tables associated with one Parent table. I need to create a user experience in which user presses Save button only once, meaning by, user enters all the data in parent model fields, then enters data in all four child model fields and then presses the save button. As far as I know, having relations in the model allows you to make associated rows inserted easily but the main problem is how to receive multiple rows from view in POST method for a single model (here I essentially mean the child models). I have tried it manually by repeating the attributes of child model in view but when I save the record, only the last rowset gets stored in the child table along with parent table, one row for the child table gets missed. Kindly note that I am using CActiveForm and other Bootstrap widgets in my View files.
Is it possible in Yii or I am too wishful....any suggestions or comments ????
Many thanks in advance.
Regards,
Faisal
I got the solution but with all the help from here and also from other forums. I followed the post by Kiran and tested it by generating additional HTML attributes using jQuery. On the submit, I got all the rows exactly how I wanted. In the controller, first I counted the total number of models submitted in the post request and then iterated over each one for desired processing. Following is the code snippet.
if(!empty($_POST))
{
$v=count($_POST['Address'])+1;
Yii::log(count($_POST['Address']));
for ($i=1; $i<$v; $i++){
$addressModel_1->attributes=$_POST['Address'][$i];
Yii::log('Dumping Data from '.$i.' model');
Yii::log($addressModel_1->city);
Yii::log($addressModel_1->street);
Yii::log($addressModel_1->state);}}
On the view side, I generated the HTML using jQuery function. All this function did was to add another set of html to allow the user to enter data. Important thing to note while generating the HTML is the name of model or else it wouldn't land where you want in controller.
Following is the code snippet of this function. Please note that I am hardcoding the "3" as id since I already had two sets of rows in DOM. I am going to further improve this code but rest assured, the logic works.
function createNewAddress(){
var newdiv = document.createElement('div');
var inner_html='<div class="row">';
inner_html+='<label for="Address_3_street">Street</label> <input name="Address[3][street]" id="Address_3_street" type="text" maxlength="200" /> </div>';
inner_html+='<div class="row">';
inner_html+='<label for="Address_3_city">City</label> <input name="Address[3][city]" id="Address_3_city" type="text" maxlength="200" /> </div> ';
inner_html+='<div class="row">';
inner_html+='<label for="Address_3_state">State</label> <input name="Address[3][state]" id="Address_3_state" type="text" maxlength="200" /> </div>';
newdiv.innerHTML=inner_html;
$('#user-form').append(newdiv);
}
This way, I can have n-number of child rows added on the fly from browser and user will save all data by pressing the Save or Submit button only once.
Thanks to everyone for their support.
Regards,
Faisal
You should be using tabular input, that way you can receive data for multipe instances of the same type, you can then save the parent and use its id to fill the child foreign keys.
You could make a new CFormModel to handle all the form fields validation, and then manually set the attributes after the $model->validate in the POST function. EG:
if ($model->validate){
$model_one = new ModelOne;
$model_one->name = $model->model_one_name;
$model_one->surname = $model->model_one_surname;
....
$model_two = new ModelTwo;
$model_two->name = $model->model_two_name;
$model_two->surname = $model->model_two_surname;
....
}

ErrorSummary for multiform model

I am using a multi form model. A $model array is passed to the view and for each model object I am trying to have an errorsummary. See the code below.
foreach ($model as $f=>$edu):
echo $form->errorSummary($edu,'');
echo $form->textField($edu,"[$f]schoolname",array('size'=>30,'maxlength'=>128));
endforeach;
When I submit the form an error summary for only one form is displayed. Any ideas.
Maybe you need to rethink your form structure, for example - put all into one form, then inside controller make validation of every model you use and then show error messages.