how to get partialview data in controller - asp.net-mvc

I am using three partialview on a single view, I have a submit button on clicking of which I want to send information to database, I have to retrieve data from all the partialview.
Can You please provide me correct information to do it.
Darin I m using L2S so when I drag my stored procedure, I get code some thing like this in
[global::System.Data.Linq.Mapping.FunctionAttribute(Name="SP_Name")]
public int SP_Name(
[global::System.Data.Linq.Mapping.ParameterAttribute(Name="EmployeeID", DbType="Int")] System.Nullable<int> EmployeeID
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), EmployeeID);
encounterID = ((System.Nullable<int>)(result.GetParameterValue(293)));
return ((int)(result.ReturnValue));
}
}
Updated
<script language="javascript" type="text/javascript">
$(function () {
$('#Form1').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
var message = data.Result;
$('#Result').html(message);
}
});
return false;
});
});
</script>
In my Controller I am using
public ActionResult Index(FormCollection frm)
{
My Code ---------------------
return Json(new { Result = "Success" });
}
When I return this I m getting a file in post back and it ask me to save it.
I have checked using flidder, in URL it shows me that the path as / only
where as If I fill any particular partialview It shows something like /Controller Name/Partialview
Can You help me with this problem

Well, sending data to a controller action is usually done by performing an HTTP request to this controller action. There are different ways of performing an HTTP request:
Use a <form> tag pointing to this action
Use AJAX
So if you go with the first approach you could have a single <form> wrapping all the partials which would have multiple submit buttons (with different names). Then when you click on one submit buttons all the input fields will be sent to the controller action and then inside the controller action you could process the data based on which submit button was clicked.
If you use the second option, well, then simply harvest the values you need to be sent uipon button click and send them along the AJAX request.
UPDATE:
As requested in the comments section here's how the first technique could be put into action. It uses two partials instead of three but it could be easily extrapolated.
As always you start by defining a view model which will represent the data you would like to work with on this particular view:
public class MyViewModel
{
public Partial1ViewModel Model1 { get; set; }
public Partial2ViewModel Model2 { get; set; }
}
public class Partial1ViewModel
{
public string Foo { get; set; }
}
public class Partial2ViewModel
{
public string Bar { get; set; }
}
Then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Model1 = new Partial1ViewModel { Foo = "foo" },
Model2 = new Partial2ViewModel { Bar = "bar" },
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// Here you have access to model.Model1.Foo and model.Model2.Bar =>
var button = "";
if (!string.IsNullOrEmpty(Request["submit1"]))
{
// submit1 button was used
button = "submit1";
}
else if (!string.IsNullOrEmpty(Request["submit2"]))
{
// submit2 button was used
button = "submit2";
}
var result = string.Format("thanks for submitting using {0}", button);
return Content(result, "text/plain");
}
}
and then a main view (~/Views/Home/Index.cshtml):
#model MyViewModel
#using (Html.BeginForm())
{
#Html.EditorFor(x => x.Model1)
#Html.EditorFor(x => x.Model2)
}
and the two corresponding editor templates (or partials if you will):
~/Views/Home/EditorTemplates/Partial1ViewModel.cshtml:
#model Partial1ViewModel
<h2>Partial 1</h2>
<div>
#Html.LabelFor(x => x.Foo)
#Html.EditorFor(x => x.Foo)
<input type="submit" value="Submit me!" name="submit1" />
</div>
~/Views/Home/EditorTemplates/Partial2ViewModel.cshtml:
#model Partial2ViewModel
<h2>Partial 2</h2>
<div>
#Html.LabelFor(x => x.Bar)
#Html.EditorFor(x => x.Bar)
<input type="submit" value="Submit me!" name="submit2" />
</div>

Related

MVC BeginCollectionItem

I'm having some issue getting my partial view BeginCollectionItem to save to the database. I have a form which has a dynamic number of "sections" that can be added to the page, and within each of these fields there is a text box where the user can enter the section name.
As far as I can tell the BeginCollectionItem within the partial view is working properly, however I cannot post the info to the database. In my other forms I have used a [bind()] to send the data to the database, is it possible to get this into a list and then post that via a bind?
I've included my code below:
The Model:
namespace project.Models.SetupViewModels
{
public class SOPTopTemplateBuilderViewModel
{
public List<Section> Section { get; set; }
}
public class Section {
public int SectionId { get; set; }
public string SectionText { get; set; }
public string TopTempId { get; set; }
}
}
cshtml:
#model IEnumerable<project.Models.SetupViewModels.Section>
#using (Html.BeginForm("SOPTopTemplateBuilder", "Setup", FormMethod.Post))
{
<div class="main-holder" id="theform">
#foreach(var item in Model)
{
#Html.Partial("_SectionCreator", item)
}
</div>
<button id="add" type="button">Add</button>
<div class="form-group submit-row">
<div class="col-12 float-to-right">
<input type="submit" class="btn btn-default" value="continue" />
</div>
</div>
}
#section Scripts {
<script>
$(document).ready(function () {
var url = '#Url.Action("AddSection")';
var form = $('form');
var recipients = $('#theform');
$('#add').click(function() {
$.post(url, function(response) {
recipients.append(response);
// Reparse the validator for client side validation
form.data('validator', null);
$.validator.unobtrusive.parse(form);
});
});
});
</script>
}
Partial View:
#model project.Models.SetupViewModels.Section
#using HtmlHelpers.BeginCollectionItemCore
#using (Html.BeginCollectionItem("Section"))
{
<div class="new-section">
<div>
<p>New Section</p>
#Html.HiddenFor(m => m.SectionId, new { #class="id" })
#Html.EditorFor(m => m.SectionText, new { #class = "form-control limit-form"})
</div>
</div>
}
Controller:
[HttpPost]
public PartialViewResult AddSection()
{
return PartialView("_SectionCreator", new Section());
}
[HttpGet]
public ActionResult SOPTopTemplateBuilder(){
List<Section> model = new List<Section>();
return View(model);
}
[HttpPost]
public ActionResult SOPTopTemplateBuilder(IEnumerable<Section> soptop)
{
if (ModelState.IsValid)
{}
return View(soptop);
}
Your use of Html.BeginCollectionItem("Section") perpends Section[xxxx] to the name attribute (where xxxx is a Guid) so that you generating inputs with
<input name="Section[xxxx].SectionId" .... />
which posts back to a model containing a collection property named Sections.
Since you already have a model with that property, you can change the POST method to
[HttpPost]
public ActionResult SOPTopTemplateBuilder(SOPTopTemplateBuilderViewModel soptop)
other options include
Using your existing POST method and omitting the "Section" prefix
using Html.BeginCollectionItem("") which will generate
name="[xxxx].SectionId"
Changing the POST method signature to public ActionResult
SOPTopTemplateBuilder(IEnumerable<Section> section) (where the
name of the parameter matches the name of the prefix)
Using a BindAttribute to 'strip' the prefix from the form values
public ActionResult SOPTopTemplateBuilder([Bind(Prefix = "Section")]IEnumerable<Section> soptop)
As a side note, your editing data, so you should always use a view model (say public class SectionViewModel) rather than using data models in your view. - What is ViewModel in MVC?

How to update view model in a partial view in MVC5?

I have a View and inside that view I have a div that will contain a partial view.
My issue is this. The user selects an item from the dropdownlist and I load the partial view with the model. The user change changes some of the textboxes and clicks the button to submit the partial view (which is in a Html.BeginForm).
When I go to examine the model in the controller the model doesn't contain the changes that the user made.
Why doesn't the model reflect the changes the user made?
In the main view:
<div id="personInfo" style="display:none;"></div>
My partial view:
#model MyProject.MyModel
#(Html.Kendo().DropDownList().Name("ddlFilters")
.AutoBind(true)
.OptionLabel("--- Select Filter ---")
.DataValueField("ID")
.DataTextField("MYFILTER")
.DataSource(ds =>
ds.Read(r => r.Action("GetPersonFilters", "Home"))
)
.Events(x => x.Select("ddlFilters_onSelect"))
)
#using (Html.BeginForm("PersonAction", "Home", FormMethod.Post, new { #class = "form-horizontal", id = "personForm" }))
{
// Strongly typed Kendo fields. Several DropDownListFor and TextBoxFor
#Html.Kendo().TextBoxFor(x => x.FirstName).HtmlAttributes(new { #class = "form-control kendoTextBox required " })
// Button to post the form data to the controller.
}
My Javascript:
function ddlFilters_onSelect(e) {
var itm = this.dataItem(e.item);
clearForm();
if (itm.ID > 0) {
// Ajax call to get data....
$.ajax({
url: "/Home/GetPerson",
type: "GET",
data: { "myID": itm.ID }
})
.done(function (result) {
//var aaa = data;
$("#personInfo").html(result);
})
.fail(function (xhr, status, err) {
alert(xhr.responseText);
});
}
};
Model:
public partial class MyModel
{
public decimal ID { get; set; }
public string FirstName{ get; set; }
public string LastName{ get; set; }
public string MiddleName{ get; set; }
}
EDIT:
Controller Code:
// Initial call to main view
public ActionResult CreateNewPerson()
{
return View();
}
// Call to load Partial View initially
public PartialViewResult GetPersonInfo()
{
return PartialView("_PersonForm", new MyModel());
}
// Call to load partial view with data
public PartialViewResult GetPerson(int myID)
{
myData = GetFromDB(myID);
return PartialView("_PersonForm", myData);
}
// Method to save partial form
[HttpPost]
public ActionResult PersonAction(MyModel filter)
{
if (ModelState.IsValid)
{
// Go update DB
}
return View("CreateNewPerson");
}
This is not exactly the scenario you described, but this is how my team uses partials:
1) In the ViewModel for your Main View, add a property (e.g. MyModel) for the Model of the partial view.
2) When calling the partial View in the cshtml, make sure you tell MVC where to bind the content of the partial View:
#Html.Partial("_PersonAction", Model.MyModel, new ViewDataDictionary(Html.ViewData) {
TemplateInfo = new TemplateInfo { HtmlFieldPrefix = Html.NameFor(m => m.MyModel).ToString() }
})
Note how we use the TemplateInfo to set the right context for the partial, so the inputs rendered in the partial are prefixed with the correct names to make the modelbinding work. E.g. <input name="MyModel.FirstName">
You can probably fake this in javascript, but don't ask me how.
3) Our controller actions accept the ViewModel of the main page. The <form> is on the main page and surrounds the partial call.

mvc parse and display contents of json in a checkbox

I am new to mvc and this is my requirement. I am developing a page which should render a text and a checkbox. The checkbox will be checked depending on the T/F value from the database. So I am passing all the necessary data from db to the view as Json object in GetData() method.
namespace ClinicalAdvantage.Web.Controllers.UserAppSettingC
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using NHibernate.Mapping;
public class UserAppSettingsController : Controller
{
private readonly IAgg1 agg;
public UserAppSettingsController(IAgg1 agg)
{
this.agg = agg;
}
#region Public Methods and Operators
public ActionResult Index()
{
return this.View();
}
public ActionResult GetData()
{
return new JsonNetResult() { Data = this.agg.GetAllUserAppSettings() };
}
public ActionResult Save(JObject userAppSettings)
{
if (userAppSettings != null)
{
this.agg.SaveAllUserAppSettings(userAppSettings);
}
return this.Json(new { Status = "Success" });
}
#endregion
}
}
I have once tried returning the same data written as a viewmodel as a result of the index(). I had done something like
public ActionResult Index()
{
return this.View(model);
}
And for this I wrote out the in the corresponding view as
#model ClinicalAdvantage.Web.ViewModels.UserAppSettings1.UserAppSettingsViewModel
<form action="#Url.Action("Save")" method="post">
#Html.CheckBoxFor(x => x.IsM, new { maxlength = "50", size = "50" })
<!-- Form content goes here -->
<input type="submit" value="Save" />
</form>
But for some reason I am not using viewmodel to return data. So the above way of coding the veiw might not be right. I am not using GetData() to pass data to the front end and I can't really change this.
public ActionResult GetData() { return new JsonNetResult() { Data = this.agg.GetAllUserAppSettings() }; }
But I want to know how to code the front end to parse this json data when I am returning it as result of GetData method as tyype JsonNetResult.. Where will my view be. What should be the code if I want to display a checkbox and save button. The checkbox will be populated based on value returned by json.
This is the json I am returning
{"MaskPatientName":{"enabled":true,"value":false}}
There should be a label called MaskPatienTName
The check box should be checked if value property is true
On click of save butoon the save method in the controller shld be called.
Please help me
Simplest solution is to pass the populated view model to the view in your Index action
public ViewResult Index()
{
return View(agg.GetAllUserAppSettings());
}
And then your view should look something like this (use the Html helper to create form markup). This assumes that IsM is a property of UserAppSettingsViewModel.
#model ClinicalAdvantage.Web.ViewModels.UserAppSettings1.UserAppSettingsViewModel
#using (Html.BeginForm("Save", "UserAppSettings")) {
#Html.CheckBoxFor(x => x.IsM, new { maxlength = "50", size = "50" })
<!-- Form content goes here -->
<input type="submit" value="Save" />
}

asp.net 4.0 MVC 3 ajax form in Overlay

I am interested in creating an AJAX form submit in a jQuery overlay. I am not sure how to approach this, do I just toss a partial view into the overlay?
I want to pass to the server the data in the form of a model so I can save it the the data base, I need to be able to create some sort of indication as to whether or not the request succeed. Can anyone guide me through this?
I am kinda new with AJax.
You could use jQuery UI Dialog. For example let's suppose that you have a view model:
public class MyViewModel
{
public string Foo { get; set; }
[Required]
public string Bar { get; set; }
}
and a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Modal()
{
return PartialView(new MyViewModel());
}
[HttpPost]
public ActionResult Modal(MyViewModel model)
{
if (!ModelState.IsValid)
{
return PartialView(model);
}
return Json(new { success = true });
}
}
In this example the Index action will serve the main view which will simply contain a link allowing to show the form as a modal dialog.
Here's the Index.cshtml view:
#Ajax.ActionLink(
"show form in modal",
"modal",
new AjaxOptions { OnSuccess = "onModalLoad" }
)
<div id="modal"></div>
and the Modal.cshtml partial which will contain the form:
#model MyViewModel
#using (Ajax.BeginForm(new AjaxOptions { OnSuccess = "onSubmitSuccess" }))
{
<div>
#Html.LabelFor(x => x.Foo)
#Html.EditorFor(x => x.Foo)
#Html.ValidationMessageFor(x => x.Foo)
</div>
<div>
#Html.LabelFor(x => x.Bar)
#Html.EditorFor(x => x.Bar)
#Html.ValidationMessageFor(x => x.Bar)
</div>
<button type="submit">OK</button>
}
The last step is to wire everything using javascript. Here are the 2 callbacks used:
var onModalLoad = function (result) {
$('#modal').html(result).dialog();
}
var onSubmitSuccess = function (result) {
if (!result.success) {
$('#modal').html(result);
} else {
alert('thanks for submitting');
$('#modal').dialog('close');
}
};
and that's it.
Don't forget to reference the jquery-ui and jquery.unobtrusive-ajax scripts to your page:
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

How to display Jquery modal dialog after server side validation error

I am very new to JQuery and MVC. In my application i am opening a JQuery modal dialog on button click. I am rendering a partial view on this dialog using controller action method which is something like:
public ActionResult Create()
{
return PartialView("Create");
}
Partial view contains some textboxes and "create" button. On create button i am trying to save data in database. But before that i do some validation like if entered name already exist then show that message to user.
I did this using following code:
return PartialView("Create", model);
this is showing the message properly but it render only partial view in browser and modal dialog gets disappeared.
Please let me know how can i show the same modal dialog with error.
You will need to use AJAX submit of the form. Here's how to proceed. As always start with a view model which will represent the information for the dialog form:
public class MyViewModel
{
public string Foo { get; set; }
[Required(ErrorMessage = "The bar is absolutely required")]
public string Bar { get; set; }
}
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
return PartialView("Create");
}
[HttpPost]
public ActionResult Create(MyViewModel model)
{
if (!ModelState.IsValid)
{
return PartialView(model);
}
// TODO: the model is valid => do some processing with it
// and return a JSON result confirming the success
return Json(new { success = true });
}
}
and a main view (~/Views/Home/Index.cshtml):
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>
<script type="text/javascript">
// Remark: all this javascript could be placed in a separate js file
// to avoid cluttering the views
$(function () {
$('#modalLink').click(function () {
$('#dialog').load(this.href, function () {
$(this).dialog();
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
alert('thanks for submitting');
$('#dialog').dialog('close');
} else {
$('#dialog').html(result);
bindForm();
}
}
});
return false;
});
}
</script>
#Html.ActionLink("open modal", "create", null, null, new { id = "modalLink" })
<div id="dialog"></div>
and a partial view (~/Views/Home/Create.cshtml) which will contain the form shown in the modal:
#model MyViewModel
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(x => x.Foo)
#Html.EditorFor(x => x.Foo)
#Html.ValidationMessageFor(x => x.Foo)
</div>
<div>
#Html.LabelFor(x => x.Bar)
#Html.EditorFor(x => x.Bar)
#Html.ValidationMessageFor(x => x.Bar)
</div>
<input type="submit" value="OK" />
}

Resources