Form with multiple answers as radio buttons in mvc - c#

I have a litle problem with mvc application. I have form, where are many questions and user have to choose one option for every answer. But when I send data to controller, data are null. Can you please help me find solution?
I have one view with form and for every question is partialview, where are stored also answers as radio buttons
main view
#using (Html.BeginForm("ConfirmTestForm", "Home", FormMethod.Post))
{
<div class="row">
<div class="col-12">
<progress id="oca-progress" class="oca-progress" max="190" value="0"></progress>
</div>
</div>
for (int i = 0; i < Model.Questions.Count; i = i + 10)
{
<div id="#($"section-{(i/10)}")" class="#(first ? "" : "oca-hidden")">
<div class="row">
<div class="col-md-8">
<h3>
Otázka
</h3>
</div>
<div class="col-md-4 text-end">
<ul class="oca-test-choices">
<li>
<div class="oca-choice-wrapper">
<span>A</span>
</div>
</li>
<li>
<div class="oca-choice-wrapper">
<span>M</span>
</div>
</li>
<li>
<div class="oca-choice-wrapper">
<span>N</span>
</div>
</li>
</ul>
</div>
</div>
<hr class="oca-hr" />
#*#for (int j = i; j < i + 10; j++)*#
#foreach (var question in Model.Questions.Skip(i).Take(10))
{
#Html.Partial("_QuestionDetail", question)
}
<div id="error-message" class="w-100 invisible oca-validation-error">
<span>Je potřeba vyplnit všechny odpovědi</span>
</div>
#if (i != Model.Questions.Count - 10)
{
<div class="row oca-row-button">
<div class="col-6 text-start">
#if (!first)
{
<input name="previous" class="oca-test-button" type="button" value="Předchozí" />
}
</div>
<div class="col-6 text-end">
<input name="next" class="oca-test-button" type="button" value="Další" />
</div>
</div>
}
else
{
<div class="row oca-row-button">
<div class="col-6 text-start">
<input name="previous" class="oca-test-button" type="button" value="Předchozí" />
</div>
<div class="col-6 text-end">
<input class="oca-test-button" type="submit" value="Další" />
</div>
</div>
}
#if (first)
{
first = false;
}
</div>
}
}
partialView with one question
<div>
<div class="row">
<div class="col-md-8">
<label>#($"{Model.Order} - {Model.Name}")</label>
</div>
<div class="col-md-4 text-end">
<ul class="oca-test-choices">
<li>
<div class="oca-choice-wrapper">
#Html.RadioButtonFor(m => m.Value, ChoiceTypes.Yes, new { #class = "oca-choice" })
#*#Html.RadioButton(Model.Order.ToString(), Model.ChoiceYes, new { #class = "oca-choice" })*#
</div>
</li>
<li>
<div class="oca-choice-wrapper">
#Html.RadioButtonFor(m => m.Value, ChoiceTypes.Maybe, new { #class = "oca-choice" })
#*#Html.RadioButton(Model.Order.ToString(), Model.ChoiceMaybe, new { #class = "oca-choice" })*#
</div>
</li>
<li>
<div class="oca-choice-wrapper">
#Html.RadioButtonFor(m => m.Value, ChoiceTypes.No, new { #class = "oca-choice" })
#*#Html.RadioButton(Model.Order.ToString(), Model.ChoiceNo, new { #class = "oca-choice" })*#
</div>
</li>
</ul>
</div>
</div>
</div>
Model
public class QuestionsViewModel
{
public List<QuestionViewModel> Questions { get; set; }
}
public class QuestionViewModel
{
public int Order { get; set; }
public string Name { get; set; }
public ChoiceTypes? Value { get; set; }
}

You can use checkbox in place of radiobutton for selecting multiple answers.
click here

Related

Unable to bind data to the razor view even though the model is not null

Even though the model is not null the required html is not rendered. This is my razor view:
#model List<Product>
#{
ViewBag.Title = "Cart";
}
#for(int i=0;i<=Model.Count()-1;i++)
{
<p>foreach triggered</p>
var image = "~/images/" + Model[i].product_image_path;
<div class="row">
<div class="col">
<div class="row">
<div class="col-md-2">
<img src="#image" alt="No image" class="img-fluid" width="60" asp-append-version="true" />
</div>
<div class="col-md-4">
<div class="row">
<div class="col">
<p class="justify-content-md-start">#Model[i].ProductName</p>
</div>
</div>
<div class="row">
<div class="col">
<p>₹#Model[i].Price</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="row">
<div class="col-md-8">
#*change quantity button*#
<div class="input-group">
<button type="submit" class="btn btn-light"> - </button>
<input type="text" class="form-control" value="#Model[i].Quantity" readonly />
<button type="submit" class="btn btn-light"> + </button>
</div>
</div>
</div>
<br />
</div>
<div class="col-md-2">
<div class="row">
<div class="col">
<button class="btn btn-danger" type="button" id="button-minus">Remove</button>
</div>
</div>
</div>
</div>
</div>
</div>
}
Here is my get action method. This is basically retrieving the product from the models. I am returning an object of List<Product>. Trying to loop over it using for loop on razor view does not seem to work.
[HttpGet]
public IActionResult Cart()
{
var model = new CartProductViewModel();
var sessionId = HttpContext.Session.Id;
var allCartItems = context.cartItems;
var allProducts = context.products;
var currentCartItem = allCartItems.Where(p => p.Product.ProductId.Equals(sessionId)).Select(p=>p).ToList();
List<Product> products = new List<Product>();
foreach (var item in currentCartItem)
{
var id = item.Product.ProductId;
if (id is null) { return View("NotFound"); }
Product prod = allProducts.Where(p => p.ProductId.Equals(id)).Select(p=>p).Single();
products.Add(prod);
}
return View(products);
}

MVC ViewModel HttpPost return value has null values

I spent some time on this problem. I'm passing a ViewModel back from my View to the Controller via a form HttpPost. However, only SelectedItemId has value. Users and Rights are null.
View model UserRightViewModel
public class UserRightViewModel
{
public string SelectedItemId { get; set; }
public SelectList Users;
public List<RightViewModel> Rights { get; set; }
}
View model RightsViewModel
public class RightsViewModel
{
public int ID { get; set; }
public string Name{ get; set; }
public bool isSelected { get; set; }
}
Controller Post
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(UserRightsViewModel _viewModel)
{
UserRightsViewModel viewModel = _viewModel;
/*value _viewModel = null for Users and Rights
/* code stuff */
return View(viewModel);
}
View
#model Web.ViewModels.UserRightsViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
#ViewBag.Title
</h1>
#*<ol class="breadcrumb">
<li><i class="fa fa-dashboard"></i> Home</li>
<li>Examples</li>
<li class="active">Blank page</li>
</ol>*#
</section>
<!-- Main content -->
<section class="content">
<!-- Default box -->
<div class="box">
<div class="box-header with-border">
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">
<i class="fa fa-minus"></i>
</button>
<button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">
<i class="fa fa-times"></i>
</button>
</div>
</div>
<br />
<div class="form-group">
#Html.LabelFor(model => model.SelectedItemId, "User", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.SelectedItemId, Model.Users, new { onchange = "redirect(this.value)", #class = "form-control" })
#Html.ValidationMessageFor(model => model.SelectedItemId)
</div>
</div>
<br />
<div class="box-body">
#for (int i = 0; i < Model.Rights.Count(); i += 2)
{
<div class="row form-group">
<div class="col-md-6">
<div class="row">
<div class="col-md-4">
<div class="col-md-6">
</div>
<div class="col-md-6">
#Html.CheckBoxFor(model => model.Rights.ElementAt(i).isSelected, new { #class = "checkbox checkbox-center" })
#Html.ValidationMessageFor(model => model.Rights.ElementAt(i).isSelected, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-8">
#Model.Rights.ElementAt(i).Denumire
</div>
</div>
</div>
<div class="col-md-6">
<div class="row">
<div class="col-md-4">
<div class="col-md-6">
</div>
<div class="col-md-6">
#Html.CheckBoxFor(model => model.Rights.ElementAt(i + 1).isSelected, new { #class = "checkbox checkbox-center" })
#Html.ValidationMessageFor(model => model.Rights.ElementAt(i + 1).isSelected, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-8">
#Model.Rights.ElementAt(i + 1).Name
</div>
</div>
</div>
</div>
}
<br />
<br />
<div class="form-group">
<div class="row">
<div class="col-md-6">
<div class="col-md-9">
</div>
<div class="col-md-3">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</div>
<div class="col-md-6">
#Html.ActionLink("Cancel", "Index", null, new { #class = "btn btn-danger" })
</div>
</div>
</div>
</div>
</div>
</section>
</div>
}
I have no idea why some values are null. Why some of values are sent and some not?
Users is null because your not (and nor should you) creating and input for each property of each SelectListItem in the SelectList (if you need to return the view you re-populate the value in the POST method). And in any case, its a field, not a property (has no { get; set; }) so the DefaultModelBinder cannot set it).
Rights is null because you cannot use .ElementAt() to generate form controls for a collection (inspect the html your generating and you will see that the name attributes have no relationship to your model). The name attributes need to be
<input name="Rights[0].ID" ... />
<input name="Rights[0].Name" ... />
<input name="Rights[0].isSelected" ... />
<input name="Rights[1].ID" ... />
<input name="Rights[1].Name" ... />
<input name="Rights[1].isSelected" ... />
....
Note that your only generating a for control for the isSelected property which on its own would be meaningless in the POST method and you will an least want to include a hidden input for the ID property.
It appears from your code that you want to generate a 2 column layout, in which case your code should be (simplified)
<div class="row form-group">
#for(int i = 0; i < Model.Rights.Count; i++)
{
<div class="col-md-6">
#Html.HiddenFor(m => m.Rights[0].ID)
#Html.CheckBoxFor(m => m.Rights[0].isSelected)
</div>
// End current 'row' and start a new one every 2nd item
if ((i + 1) % 2 == 0)
{
#:</div><div class="row form-group">
}
}
</div>
Hi here is answer for your doubt, some values are posting and some values are not.
Actually you are getting the correct result and everything works perfectly
I said this because, if you bind selectedid and selectlistitem to the dropdownlistfor helper, then you will get only selectedid which was assigned as a name for the dropdownlist control. so when post, browser has sent name value pair.
This is same reason for checkbox also , which property has binded to the name that only you will get it in the post.
Hope above information was helpful
Thanks
Karthik
I can see you put submit button outside form. so form not submitting property.

mvc edit return value but db doesnt update

i have mvc project to register new student and give him courses and degree,etc, as shown in the database(i use entity framework) database of the project
. the edit view code is :
#model IList<HighStudy.Models.Grade>
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title" align="center">Student Info</h3>
</div>
<div class="panel-body">
<div class="col-lg-4">
<p>Name: #Html.DisplayFor(model => model[0].Student.Name)</p>
<p>Level: #Html.DisplayFor(model => model[0].Student.Level)</p>
</div>
<div class="col-lg-4">
<p>Department: #Html.DisplayFor(model => model[0].Student.Department)</p>
<p>Study Type: #Html.DisplayFor(model => model[0].Student.StudyType)</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-6">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title" align="center">Course 1</h3>
</div>
<div class="panel-body">
<ul class="list-group">
#for (var i = 0; i < Model.Count; i++)
{
if (Model[i].CourseNumber == 1)
{
if (Model[i].Mark == "A" || Model[i].Mark == "B")
{
<li class="list-group-item list-group-item-success">
<div class="row">
<div class="col-lg-8">
#Model[i].Cours.Course_Title
#Html.TextBoxFor(model => Model[i].Cours.Course_Title, new { style = "width:50%" })
#Html.ValidationMessageFor(model => Model[i].Cours.Course_Title)
</div>
<div class="col-lg-2">
#Model[i].Grade1
#Html.TextBoxFor(model => Model[i].Grade1, new { style = "width:30px" })
#Html.ValidationMessageFor(model => Model[i].Grade1)
</div>
<div class="col-lg-2">
#Model[i].Mark
#Html.TextBoxFor(model => Model[i].Mark, new { style = "width:30px" })
#Html.ValidationMessageFor(model => Model[i].Mark)
</div>
</div>
</li>
}
else
{
<li class="list-group-item list-group-item-danger">
<div class="row">
<div class="row">
<div class="col-lg-8">
#Model[i].Cours.Course_Title
#Html.TextBoxFor(model => Model[i].Cours.Course_Title, new { style = "width:50%" })
#Html.ValidationMessageFor(model => Model[i].Cours.Course_Title)
</div>
<div class="col-lg-2">
#Model[i].Grade1
#Html.TextBoxFor(model => Model[i].Grade1, new { style = "width:30px" })
#Html.ValidationMessageFor(model => Model[i].Grade1)
</div>
<div class="col-lg-2">
#Model[i].Mark
#Html.TextBoxFor(model => Model[i].Mark, new { style = "width:30px" })
#Html.ValidationMessageFor(model => Model[i].Mark)
</div>
</div>
</div>
</li>
}
}
}
</ul>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title" align="center">Course 2</h3>
</div>
<div class="panel-body">
<ul class="list-group">
#for (var i = 0; i < Model.Count; i++)
{
if (Model[i].CourseNumber == 2)
{
if (Model[i].Mark == "A" || Model[i].Mark == "B")
{
<li class="list-group-item list-group-item-success">
<div class="row">
<div class="col-lg-8">
#Model[i].Cours.Course_Title
#Html.TextBoxFor(model => Model[i].Cours.Course_Title, new { style = "width:50%" })
#Html.ValidationMessageFor(model => Model[i].Cours.Course_Title)
</div>
<div class="col-lg-2">
#Model[i].Grade1
#Html.TextBoxFor(model => Model[i].Grade1, new { style = "width:30px" })
#Html.ValidationMessageFor(model => Model[i].Grade1)
</div>
<div class="col-lg-2">
#Model[i].Mark
#Html.TextBoxFor(model => Model[i].Mark, new { style = "width:30px" })
#Html.ValidationMessageFor(model => Model[i].Mark)
</div>
</div>
</li>
}
else
{
<li class="list-group-item list-group-item-danger">
<div class="row">
<div class="col-lg-8">
#Model[i].Cours.Course_Title
#Html.TextBoxFor(model => Model[i].Cours.Course_Title, new { style = "width:50%" })
#Html.ValidationMessageFor(model => Model[i].Cours.Course_Title)
</div>
<div class="col-lg-2">
#Model[i].Grade1
#Html.TextBoxFor(model => Model[i].Grade1, new { style = "width:30px" })
#Html.ValidationMessageFor(model => Model[i].Grade1)
</div>
<div class="col-lg-2">
#Model[i].Mark
#Html.TextBoxFor(model => Model[i].Mark, new { style = "width:30px" })
#Html.ValidationMessageFor(model => Model[i].Mark)
</div>
</div>
</li>
}
}
}
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<input type="submit" value="Save" class="btn btn-default" />
</div>
}
<div class="col-lg-offset-0">
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
and in the controller code for the edit view is :
edit view code in the controller
. when it reach db.Entry(g).State = System.Data.Entity.EntityState.Modified;
it goes to catch block!!
any help will be useful, thanks in advance.
I believe you should iterate over your collection to add each object to the context, and set it to Modified.
foreach(grade in g)
{
db.Entry(grade).State = EntityState.Modified;
}
db.SaveChanges();
You must do SaveChanges outside the foreach statement
db.Entry(g).State = System.Data.Entity.EntityState.Modified;
In the above code you are getting g from another object, you need to originate it from the same db object which you are using to change the State
another things could be the list, I think state of List can't be modified altogether.
consider doing something like this
foreach (var item in g)
{
db.Set<Grade>().Attach(item);
db.Entry<Grade>(item).State = EntityState.Modified;
db.Configuration.ValidateOnSaveEnabled = false;
}
db.SaveChanges();
Recently gone through the same error, and foreach saved my life. Not sure if its a very clean way to do it.
SOLVED
my current exception was :
( Unable to update the EntitySet - because it has a DefiningQuery and no element exists in the element to support the current operation
steps that solve it :
delete all duplicate #html.hiddenfor(model=> model.StudentID) in the edit view
Right click on .edmx file and chose open with xml editor
search for DefiningQuery and Remove it, yes Remove it
search for ( store:Schema="dbo" ) and rename it to ( Schema="dbo" )
these were the steps that saved my life, thank you all my friends for help, i really appreciate your help

Model Error Not Showing after Http Post MVC 4

I am validating date input server side and adding ModelError if user input is invalid. Following is my code
public ActionResult EditOffer()
{
var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
using (joyryde_storeEntities context = new joyryde_storeEntities())
{
var objOffer = context.tbl_offer.Where(x => x.LNG_OFFER_ID == offerID).FirstOrDefault();
ViewBag.OfferID = offerID;
ViewBag.Header = "Edit " + objOffer.TXT_OFFER_TITLE;
ViewBag.ActionToPerform = "Edit";
if (System.IO.File.Exists(Server.MapPath(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], offerID))))
{
objOffer.TXT_OFFER_SMALL_PATH = string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], offerID);
}
return View("AddOffer", objOffer);
}
}
[HttpPost]
public ActionResult EditOffer(tbl_offer modal, string Add, string Edit)
{
if (ModelState.IsValid)
{
using (joyryde_storeEntities context = new joyryde_storeEntities())
{
var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
if (!isOfferExist(modal.DAT_START_OFFER.Value.Date, modal.DAT_END_OFFER.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(999), Convert.ToInt64(Session["StoreID"]), offerID, Add, Edit, context))
{
// My Code
return RedirectToAction("AllOffers", "Store");
}
else
{
ModelState.AddModelError("DAT_START_OFFER", "Date Not Available"); // Here i am adding Modal Error For Date
if (Edit != null)
{
return RedirectToAction("EditOffer");
}
else
{
return RedirectToAction("AddOffer");
}
}
}
}
else
{
return RedirectToAction("EditOffer");
}
View
<div class="panel-body container-fluid">
#using (Html.BeginForm("EditOffer", "Store", FormMethod.Post, new { #class = "form-horizontal", enctype = "multipart/form-data" , id="offerForm"}))
{
#Html.AntiForgeryToken();
#Html.ValidationSummary(true);
<div class="form-group">
<label class="col-sm-3 control-label">Offer Title</label>
<div class="col-sm-6">
#Html.TextBoxFor(model => model.TXT_OFFER_TITLE, new { #class = "form-control", placeholder = "Offer Title", autocomplete = "off", name = "title" })
#Html.ValidationMessageFor(model => model.TXT_OFFER_TITLE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Offer Banner</label>
<div class="col-sm-9">
<div class="image-container" style=" border: 1px solid #ccc; display: table;position:relative">
<a href="#editimage" data-toggle="modal" class="btn btn-sm btn-icon btn-inverse btn-round btn-image-edit" data-toggle="tooltip" data-original-title="Edit">
<i class="icon wb-pencil" aria-hidden="true"></i>
</a>
<div class="img-preview preview-lg">
<img id="image_upload_preview" src="#Url.Content(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], ViewBag.OfferID))" style="width:100%" alt="your image" />
</div>
</div>
<div class="input-group-file" style="margin-top:5px">
#Html.TextBoxFor(modal => modal.TXT_OFFER_SMALL_PATH, new { #class = "hide", #readonly = "true", width = "0", id = "filePath" })
#Html.ValidationMessageFor(modal => modal.TXT_OFFER_SMALL_PATH, "", new { #class = "text-danger" })
<span class="">
<span class="btn btn-success btn-small btn-file">
Upload Image <i class="icon wb-upload" aria-hidden="true"></i>
<input type="file" name="files" accept="image/*" multiple="" id="fileupload" onchange="showimagepreview(this)">
</span>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Offer Detail </label>
<div class="col-sm-6">
#Html.TextAreaFor(model => model.TXT_OFFER_TEXT, new { #class = "form-control", placeholder = "Offer Text", autocomplete = "off", name = "text" })
#Html.ValidationMessageFor(model => model.TXT_OFFER_TEXT, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Valid For</label>
<div class="col-sm-4">
<div class="input-daterange" data-plugin="datepicker">
<div class="input-group">
<span class="input-group-addon">
<i class="icon wb-calendar" aria-hidden="true"></i>
</span>
#Html.TextBoxFor(model => model.DAT_START_OFFER, "{0:dd MMMM yyyy}", new { #class = "form-control from_date", placeholder = "Start Date", autocomplete = "off", name = "start" })
#Html.ValidationMessageFor(model => model.DAT_START_OFFER, "", new { #class = "text-danger" })
</div>
<div class="input-group">
<span class="input-group-addon">to</span>
#Html.TextBoxFor(model => model.DAT_END_OFFER, "{0:dd MMMM yyyy}", new { #class = "form-control to_date", placeholder = "End Date", autocomplete = "off", name = "end" })
#Html.ValidationMessageFor(model => model.DAT_END_OFFER, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Is Premium</label>
<div class="col-sm-4">
<div class="radio-custom radio-default radio-inline">
#Html.RadioButtonFor(model => model.INT_IS_PRIME, 1, new { #id = "ispremiumYes", name = "ispremium", #checked = "checked" })
<label for="ispremiumYes">Yes</label>
</div>
<div class="radio-custom radio-default radio-inline">
#Html.RadioButtonFor(model => model.INT_IS_PRIME, 0, new { #id = "ispremiumNo", name = "ispremium", })
<label for="ispremiumNo">No</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-6 col-sm-offset-3">
<button type="submit" name="#ViewBag.ActionToPerform" class="btn btn-primary">Submit </button>
<button type="reset" class="btn btn-default btn-outline">Reset</button>
</div>
</div>
#Html.Hidden("cropWidth", new { id = "cropWidth" })
#Html.Hidden("cropHeight", new { id = "cropHeight" })
#Html.Hidden("cropPointX", new { id = "cropPointX" })
#Html.Hidden("cropPointY", new { id = "cropPointY" })
#Html.Hidden("ImgSrc", new { id = "ImgSrc" })
}
<div class="modal fade" id="editimage" aria-labelledby="modalLabel" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document" style="width:1024px;height:768px">
<div class="modal-content ">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="modalLabel">Crop the image</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-9">
<div class="cropper text-center">
<img id="image" src="#Url.Content(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], ViewBag.OfferID))" style="max-width:730px;" alt="Picture">
</div>
</div>
<div class="col-sm-3">
<div class="docs-preview clearfix">
<div class="img-preview preview-lg"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
But Modal Error is not showing on view. What could be the cause ?
When you set your model error then you use RedirectToAction, what mean that you load new page, check in your debug, after that your code go back to GET method and everything is reloaded.
You have to return your View with model.
ModelState.AddModelError("DAT_START_OFFER", "Date Not Available");
if (Edit != null)
{
return View(modal); //if your model is object named modal
}
You didn't see any error because of RedirectToAction. You should use the "View" method. For example you can just write return EditOffer()
If you use return RedirectToAction("EditOffer"); the error will not been show it will be redirect to public ActionResult EditOffer(){} Action method, the [HttpGet] will be shown. To rectify this error, you should use View() method. like return View(); it return the error to the form data posted page.
[HttpPost]
public ActionResult EditOffer(tbl_offer modal, string Add, string Edit)
{
if (ModelState.IsValid)
{
using (joyryde_storeEntities context = new joyryde_storeEntities())
{
var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
if (!isOfferExist(modal.DAT_START_OFFER.Value.Date, modal.DAT_END_OFFER.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(999), Convert.ToInt64(Session["StoreID"]), offerID, Add, Edit, context))
{
// My Code
return RedirectToAction("AllOffers", "Store");
}
else
{
ModelState.AddModelError("DAT_START_OFFER", "Date Not Available"); // Here i am adding Modal Error For Date
if (Edit != null)
{
return View(modal);
}
else
{
return RedirectToAction("AddOffer");
}
}
}
}
else
{
ViewBag.OfferID = Here give the office id;
ViewBag.Header = "Edit " + objOffer.TXT_OFFER_TITLE;
ViewBag.ActionToPerform = "Edit";
ModelState.AddModelError("","Your Error Message"); // Here i am adding Modal Error For Date
return View(modal);
}
}

How to use 2 buttons on the same asp.net mvc form

In my asp.net mvc form I have 2 buttons, one to save which will save data from the from in a list in sharepoint and the second button does the same and additionally it applies some css colors.
I doubt however how to use 2 actions on the same form (same controller)
this is my view
#{
Layout = "~/Views/Shared/_LayoutPage2.cshtml";
}
#using (Html.BeginForm("Index", "Movies", FormMethod.Post))
{
<div class="row">
<div class="col-md-8">
<div class="col-xs-6 col-sm-3" id="stylesheet">Hojas de estilos</div>
<div class="col-xs-6 col-sm-3">
#Html.DropDownList("cssFiles", (IEnumerable<SelectListItem>)ViewBag.cssFiles, "Crear Nuevo", new { #class = "form-control", #id = "selCssFile" })
<span>
<input type="text" class="form-control" id="txtFileName" style="display:none;" placeholder="Nombre del archivo">
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8">
Color base, links, botones, borde encabezado y pie
</div>
<div class="col-md-4">
<div id="colorSelector" class="colorSelector"><div style="background-color: #0000ff"></div></div>
</div>
</div>
<div class="row">
<div class="col-md-8">
Fondo de la pagina, fondo de los cuadros
</div>
<div class="col-md-4">
<div id="colorSelector2" class="colorSelector"><div style="background-color: #0000ff"></div></div>
</div>
</div>
<div class="row">
<div class="col-md-8">
Navegación
</div>
<div class="col-md-4">
<div id="colorSelector3" class="colorSelector"><div style="background-color: #0000ff"></div></div>
</div>
</div>
<div class="row">
<div class="col-md-8">
Navegación (Item seleccionado)
</div>
<div class="col-md-4">
<div id="colorSelector4" class="colorSelector"><div style="background-color: #0000ff"></div></div>
</div>
</div>
<div class="row">
<div class="col-md-8">
Pie de página
</div>
<div class="col-md-4">
<div id="colorSelector5" class="colorSelector"><div style="background-color: #0000ff"></div></div>
</div>
</div>
<div class="row" id="buttons">
<div class="col-md-8">
</div>
<div class="col-md-4">
<button type="button" class="btn btn-success">Guardar</button>
<button type="button" class="btn btn-primary">Guardar y aplicar</button>
</div>
</div>
}
My index action on the customize controller so far
public class CustomizeController : Controller
{
// GET: Customize
public ActionResult Index()
{
User spUser = null;
var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
using (var cc = spContext.CreateUserClientContextForSPHost())
{
int aprovisionado = (int)cc.Web.GetPropertyBagValueInt("Vinculosc.PlantillasIntranet.Aprovisionado", 0);
if (aprovisionado == 0)
{
string libraryName = "ConfiguraciónColores";
Dictionary<string, string> fields = new Dictionary<string, string>();
fields.Add("Color1", "Text");
fields.Add("Color2", "Text");
fields.Add("Color3", "Text");
fields.Add("Color4", "Text");
fields.Add("Color5", "Text");
//ProvisionTemplate(cc);
CreateLibrary(cc, libraryName);
AddFields(cc, libraryName, fields);
}
}
#region comments
/*Uri hostWeb = new Uri(Request.QueryString["SPHostURL"]);
using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity))
{
var web = clientContext.Web;
clientContext.Load(web, w => w.Lists.Include(l => l.Title).Where(l => !l.hidden));
clientContext.ExecuteQuery();
return View(web.Lists);
}*/
#endregion
return View();
}
You can put the same name in the view with different value
<button type="submit" name="Guardar" value="guardar" class="btn btn-success">Guardar</button>
<button type="submit" name="Guardar" value="aplicar" class="btn btn-primary">Guardar y aplicar</button>
And in the Controller you can check the value of the button
if (Request["Guardar"].ToString() == "guardar")
{
//Your code for the first button
}
else
{
//Your code for the second button
}
Your button type should be "submit", and you can give them a name... Same name, that can be reused in a model, or by Request.Form["GiveAName"]
Your controller should have a
[HttpPost]
public ActionResult Index()
{
... Your code to retrieve form values
}
Anyway that's bad coding... You should work with models to inject on the view, that same model could be retrieved back and so you don't have to worry about retrieving form values. :=)

Categories

Resources