i have some problems with my input data in asp.net mvc on controller site. My model include another model which is binded on some textboxs.
My main model Order include a model Customer (with a string property of first name).
Example main page (i use dev express controls), i give the model to the group:
#model Models.Order
#using (Html.BeginForm("Index", "Main"))
{
<div>
#Html.DevExpress().NavBar(settings =>
{
settings.Name = "nbWebshopSteps";
settings.EnableClientSideAPI = true;
settings.Width = new Unit(100, UnitType.Percentage);
settings.Groups.Add(group =>
{
group.Text = "Bestellung bestätigen";
group.Expanded = false;
group.ShowExpandButton = DefaultBoolean.False;
group.ContentStyle.Border.BorderColor = Color.FromArgb(247, 242, 212);
group.SetHeaderTemplateCollapsedContent(c => Html.RenderPartial("../Main/NavBarHeaderCollapsed", c.Group));
group.SetHeaderTemplateContent(c => Html.RenderPartial("NavBarHeader", c.Group));
group.SetContentTemplateContent(c => Html.RenderPartial("PersonalData", Model));
});
}).GetHtml()
}
My personal data pagem, which is rendered into the group (it comes from a dll):
#model Objects.Customer <div>
#Html.DevExpress().TextBox(settings =>
{
settings.Name = "txtFirstName";
settings.Properties.Caption = "Vorname";
settings.EncodeHtml = false;
settings.Properties.CaptionStyle.Font.Size = 14;
settings.Width = 385;}).Bind(Model.Firstname).GetHtml()</div>
After the postback my customer model is empty (first name).
[HttpPost]
public ActionResult Index(Order order)
{
}
Can someone help me?
Thanks
Take a look at this article.
DevExpress support recommend to use code like this:
#Html.DevExpress().TextBox(settings => {
//settings.Name = "Street";
settings.Name = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName("Street");
}).Bind(Model.Street).GetHtml()
Related
I want to, pass the list of objects, from view to the controller's action. I gave "List<API_VM> model, IList<API_VM> model, API_VM[] model" as parameters on action and I gave "IList<API_VM>, List<API_VM>" as model on View page. but it doesn't work. Model is null all time.
[HttpGet]
public IActionResult UrunlerListe(API_VM model)
{
XElement stok = XElement.Load(model.TedarikciLink);
List<API_VM> ApiList = new List<API_VM>();
model.Stoklar = stok.Descendants(model.ParentElement).ToList();
ViewBag.Tedarikci = model.TedarikciLink;
foreach (var item in model.Stoklar)
{
API_VM api = new API_VM();
api.UrunAdi = item.Element(model.UrunAdi).Value;
api.Kategori = item.Element(model.Kategori).Value;
api.UrunAciklama = item.Element(model.UrunAciklama).Value;
api.UrunFiyat = item.Element(model.UrunFiyat).Value;
api.UrunMarka = item.Element(model.UrunMarka).Value;
api.PaketAgirligi = item.Element(model.PaketAgirligi).Value;
api.PaketGenisligi = item.Element(model.PaketGenisligi).Value;
api.PaketUzunlgu = item.Element(model.PaketUzunlgu).Value;
api.PaketYuksekligi = item.Element(model.PaketYuksekligi).Value;
api.StokAded = item.Element(model.StokAded).Value;
api.UrunFoto1 = item.Element(model.UrunFoto1).Value;
api.UrunFoto2 = item.Element(model.UrunFoto2).Value;
api.UrunFoto3 = item.Element(model.UrunFoto3).Value;
api.UrunFoto4 = item.Element(model.UrunFoto4).Value;
api.UrunFoto5 = item.Element(model.UrunFoto5).Value;
api.UrunFoto6 = item.Element(model.UrunFoto6).Value;
ApiList.Add(api);
}
return View(ApiList);
}
#model IList<API_VM>
#{
ViewData["Title"] = "UrunlerListe";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<form asp-action="UrunlerListe" method="post">
#for (int i = 0; i <Model.Count(); i++)
{
#Html.TextBoxFor(model => Model[i].UrunAdi)
}
<input type="submit" value="ürünleri gönder" />
</form>
[HttpPost]
public IActionResult UrunlerListe(API_VM[] model)
{
//work
}
Refer List of Model Object Post to Controller in ASP.NET MVC , this is similar to your requirement.
Moreover you can also refer Pass (Send) List of objects from View to Controller using jQuery AJAX in ASP.Net MVC this article.
Hi i have one registration page and it contain fields called UID,UserName,Password. I am using dev Express gridview. When i click the edit button it need to pass the particular row key value to controller but it passing null parameter to controller. Now what i want is i want to pass the particular row key Parameter to controller by clicking edit button in grid view in mvc dev express gridview using SetDataItemTemplateContent.Below i post my code please any one correct my code and tell me what mistake i did.
My Model (UserMasterViewModel)
public int UID{get;set;}
public string UserName{get;set;}
public string Password{get;set;}
My Controller Code
Public ActionResult UserMasterEdit(int? id)
{
View_MUsrRegistration userregistrartion = db.MUsrRegistration.Find(id)
UserMasterViewModel usermasterviewmodel = new UserMasterViewModel();
usermasterviewmodel.UserName = userregistrartion.UserName;
usermasterviewmodel.Password = userregistrartion.Password;
return View(usermasterviewmodel)
}
Grid View Code
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "gvEditing";
settings.KeyFieldName = "UID";
settings.CallbackRouteValues = new { Controller = "UserMaster", Action = "UserMasterPartial" };
settings.Width = Unit.Percentage(100);
settings.Columns.Add(column => {
column.Caption = "#";
column.SetDataItemTemplateContent(c =>
{
ViewContext.Writer.Write(
Html.ActionLink("Edit", "UserMasterEdit", new { UID = DataBinder.Eval(c.DataItem, "UID") }) + " " +
Html.ActionLink("Delete", "UserMasterDelete", new { ProductID = DataBinder.Eval(c.DataItem, "UID") },
new { onclick = "return confirm('Do you really want to delete this record?')" })
);
});
column.Settings.AllowDragDrop = DefaultBoolean.False;
column.Settings.AllowSort = DefaultBoolean.False;
column.Width = 70;
});
settings.Columns.Add("UserName");
settings.Columns.Add("Password");
settings.ClientLayout = (s, e) =>
{
if(e.LayoutMode == ClientLayoutMode.Loading) {
if(Session["GridState"] != null)
e.LayoutData = (string)Session["GridState"];
}
else
Session["GridState"] = e.LayoutData;
};
}).Bind(Model).GetHtml()
EDIT View
#model MSSERP.Models.UserMasterViewModel
#{
Html.EnableClientValidation();
}
#using(Html.BeginForm("UserMaterUpdate", "UserMaster", FormMethod.Post, new { #class = "edit_form" })) {
#Html.HiddenFor(m=>m.UID)
<div class="line">
#Html.Label(UserNmae)
#Html.TextBoxFor(m=>m.UserName)
</div>
<div class="line">
#Html.Label(Password)
#Html.TextBoxFor(m=>m.Password)
</div>
<div class ="line">
<input type="submit" value ="Save"/>
</div>
In this i am clicking edit button it passing the null value to controller. I tried many ways but cant able to pass the UID parameter to controller.
i donno what mistake i did in this action. I tried my level best to explain this issue Any one understand and help me to resolve this issue.
Thanks..
Try the following'
Change:
Html.ActionLink("Edit", "UserMasterEdit", new { UID = DataBinder.Eval(c.DataItem, "UID") })
To:
Html.ActionLink("Edit", "UserMasterEdit", new { id = DataBinder.Eval(c.DataItem, "UID") }, null)
The parameter name should match the controller's parameter name.
The added null argument is needed to ensure that the right parsing method is called. see this link:HTML.ActionLink method
In the GridView where your DisplayFor's are located:
<a class="ml-2" href="/Merchant/Merchant_Boarding/#Html.DisplayFor(modelItem => item.GUID)" title="Edit">Edit</a>
Or use an ActionLink:
#Html.ActionLink("Edit", "Merchant_Boarding", new { id = (item.GUID) }, new { #class = "ml-2" })
In your Get:
[HttpGet]
public IActionResult Merchant_Boarding(string? id)
{
var model = new MerchantDetail();
MerchantData merchdata = new MerchantData();
model = merchdata.RetrieveMerchantData(id);
merchdata.Dispose();
return View(model);
}
The id variable will contain the value you passed in from the grid view. From there, you can populate your model and show it.
I have a devExpress xtraReport that is being supplied by a strongly typed dataset. As long as I'm hard coding two parameters into the Actions, it loads the data into the dataset and displays in the report. Once I try to make it pass the values from the main page down through the partial, it fails. My first attempt was to pass the parameters through the ViewBag, wasn't working, so switched to a model, still not working right.
main page controller
public ActionResult SubsequentVisitReport(int noteType = 1, int noteId = 9)
{
ViewBag.noteType = noteType;
ViewBag.noteId = noteId;
ReportParameters reportParamters = new ReportParameters();
reportParamters.noteType = noteType;
reportParamters.noteId = noteId;
return View(reportParamters);
}
main page cshtml - added in the EditorFor to make sure the model makes it there (it does). Have tried calling the Partial both with and without putting 'Model'
#model ReportParameters
#Html.EditorFor(m => m.noteId)
#Html.EditorFor(m => m.noteType)
#Html.HiddenFor(m => m.id)
#Html.HiddenFor(m => m.noteType)
#Html.HiddenFor(m => m.noteId)
#Html.Partial("_SubsequentVisitReport", Model)
controller for the partial - this does not receive the data from the model and I don't understand why. The model is NOT null, all the values are 0 (zero).
[HttpPost]
public ActionResult _SubsequentVisitReport(ReportParameters model)
{
int noteType = model.noteType;
int noteId = model.noteId;
rptSubsequentVisit report = new rptSubsequentVisit();
try { report.DataSource = getSubsequentVisitData(model.noteType, model.noteId).Tables[0]; }
catch { return RedirectToAction("Not_Authorized"); }
ViewData["Report"] = report;
return PartialView("_SubsequentVisitReport");
}
The view for the partial
#model ReportParameters
#Html.HiddenFor(m => m.id)
#Html.HiddenFor(m => m.noteType)
#Html.HiddenFor(m => m.noteId)
#Html.DevExpress().DocumentViewer(settings =>
{
// The following settings are required for a Report Viewer.
settings.Name = "reportViewer1";
settings.Report = (rptSubsequentVisit)ViewData["Report"];
// Callback and export route values specify corresponding controllers and their actions.
// These settings are required as well.
settings.CallbackRouteValues = new { Controller = "Reports", Action = "_SubsequentVisitReport"};
settings.ExportRouteValues = new { Controller = "Reports", Action = "_SubsequentVisitReportExport" };
}).GetHtml()
The data needs to persist through the partial both to load the note for viewing, but also for the export function.
What am I doing wrong, or is there another better way to do this?
Thanks,
Dave K.
The settings.CallbackRouteValues object tells the DocumentViewer where to request the actual report, and it can take parameters. Unfortunately it will be a separate request, so you can't send your model, only simple values that can be passed as strings. In this example, they are using a custom model for the report, but the model has to be re-created from raw values in each action.
If you convert your partial action to take integer parameters:
public ActionResult _SubsequentVisitReport(int noteType, int noteId)
you should be able to tack those arguments on the end of the CallbackRouteValues:
settings.CallbackRouteValues = new { Controller = "Reports",
Action = "_SubsequentVisitReport",
noteType = model.noteType,
noteId = model.noteId};
I have multiple index views with a different grid in each of these views, but all of them uses the same popup control. I dont want to make a partial view foreach index view that i have. So i put the popup partial view in the Shared folder.
But i have a Html.BeginForm('Action','Controller') in the popup partialview, and these values are different in each grid. How can i pass these from the view of the grid to the partial view of the popup?
The Grid View:
//Code Resumed
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "TestMasterGrid";
settings.Column.Add("Id");
settings.Column.Add("Name");
settings.Column.Add("Email");
//Command Column Wich calls the popup control
}
The PopUp PartialView:
//Code resumed
using (Html.BeginForm("ActionINeedToGetFromTheGridView", "ControllerINeedToGetFromTheGridView", FormMethod.Post))
{
Html.DevExpress().TextBox(
textBoxSettings =>
{
textBoxSettings.Name = "reason";
textBoxSettings.ControlStyle.CssClass = "editor";
})
.Render();
Html.DevExpress().Label(
labelSettings =>
{
labelSettings.Name = "sh";
labelSettings.ControlStyle.CssClass = "label";
}).Render();
Html.DevExpress().Button(
buttonSettings =>
{
buttonSettings.Name = "btnUpdate";
buttonSettings.ControlStyle.CssClass = "button";
buttonSettings.Width = 80;
buttonSettings.Text = "OK";
buttonSettings.UseSubmitBehavior = true;
}
)
.Render();
Thanks!
Pass the action and controller names to the action that returns the PartialViewResult. Then, pass the names to the partial's model and use them in the BeginForm statement:
Html.BeginForm(Model.Action, Model.Controller, FormMethod.Post)
Edit:
I'm not very familiar with DevExpress, but I found the CallbackRouteValues member in settings. I'll use that for my example:
settings.CallbackRouteValues = new { Controller = "ControllerName", Action = "GetPartialView", desiredAction = "DesiredAction", desiredController = "DesiredController" }
In your controller, you'd have the action and controller parameters:
public PartialViewResult GetParialView(string desiredAction, string desiredController) {
var viewModel = new PartialViewModel { Action = desiredAction, Controller = desiredController);
Return PartialView("Name", viewModel);
}
I typed out this code by hand, so it's probably full of errors. Hopefully it gets the idea across, though.
Quick edit: changed some parameter names to make it a little clearer.
I'm having a little issue with an Edit view on a ViewModel. When I post my Edit view to the server for the first time, it needs to return the Edit view again with the same ViewModel where the database ID has been appended to.
This is the Edit method in the appropriate controller:
[HttpPost]
public ActionResult Edit(InvoiceDetailsViewModel invoice) {
using (var context = new HyperContext(WebSecurity.CurrentUserId)) {
if (ModelState.IsValid) {
if (invoice.ID == 0) {
var dbItem = Mapper.Map<eu.ecmt.RecruitmentDatabase.Models.Invoice>(invoice);
context.Invoices.Add(dbItem);
context.SaveChanges();
var newInvoice = Mapper.Map<InvoiceDetailsViewModel>(dbItem);
FillViewBag(context, newInvoice);
newInvoice.Description = "TEST";
return PartialView(newInvoice);
}
else {
context.Entry(Mapper.Map<eu.ecmt.RecruitmentDatabase.Models.Invoice>(invoice)).State = System.Data.EntityState.Modified;
context.SaveChanges();
return Content(Boolean.TrueString);
}
}
FillViewBag(context, invoice);
return PartialView(invoice);
}
}
The relevant part here is where the invoice.ID is 0, the invoice is saved to the DB to get an ID and returned to the Edit view.
In that view I got these lines for starters:
#model eu.ecmt.RecruitmentDatabase.ViewModels.InvoiceDetailsViewModel
#using (Html.BeginForm("Edit", "Invoice", FormMethod.Post, new { id = "invoices-edit-form" })) {
#Html.ValidationSummary(true)
<script type="text/javascript">
$(document).ready(function () {
//$("#tabs").tabs();
InitProfileUI();
});
</script>
if (Model.ID != 0) {
<script type="text/javascript">
$(document).ready(function () {
LoadList('/InvoiceDetail/List/#Model.ID', '', 'invoice-details');
});
</script>
}
<fieldset>
<legend>Edit contract</legend>
#Html.HiddenFor(m => m.ID)
#Html.HiddenFor(m => m.InvoiceNumber)
#Html.HiddenFor(m => m.Created)
#Html.HiddenFor(m => m.CreatedBy)
#Html.HiddenFor(m => m.Modified)
#Html.HiddenFor(m => m.ModifiedBy)
When first rendering this view, the script element containing the LoadList call is not in the output. When the form is posted and the view is rendered with the updated viewmodel, that element is in the output. The hidden field containing the ID of the invoice, though, still shows 0. So, in essence, what is happening here, is that the Model object in the ViewData dictionary is the correct version, the object that is being used in the expressions seems to be another, older, version.
Anyone care to explain this and point me into the right direction?
It seems to be behavior by design, according to this post.
Summary: the HTMLHelper will first use the values in the POST, then it will use the values from the actual model. Removing them from ModelState in the controller method did the trick:
[HttpPost]
public ActionResult Edit(InvoiceDetailsViewModel invoice) {
using (var context = new HyperContext(WebSecurity.CurrentUserId)) {
if (ModelState.IsValid) {
if (invoice.ID == 0) {
ModelState.Remove("ID");
ModelState.Remove("Created");
ModelState.Remove("CreatedBy");
ModelState.Remove("Modified");
ModelState.Remove("ModifiedBy");
var dbItem = Mapper.Map<eu.ecmt.RecruitmentDatabase.Models.Invoice>(invoice);
context.Invoices.Add(dbItem);
context.SaveChanges();
invoice = Mapper.Map<InvoiceDetailsViewModel>(dbItem);
FillViewBag(context, invoice);
return PartialView(invoice);
}
else {
context.Entry(Mapper.Map<eu.ecmt.RecruitmentDatabase.Models.Invoice>(invoice)).State = System.Data.EntityState.Modified;
context.SaveChanges();
return Content(Boolean.TrueString);
}
}
FillViewBag(context, invoice);
return PartialView(invoice);
}
}