There's some problem in "mixing ways" to do posts requests? - c#

For example, in my project I'm using #using(Html.BeginForm(some stuff))to create an instance of my model and finally appending it to my database. But, when I'm editing (updating) some object of model, I'm usingn ajax get to retrieve data and finally using #Html.BeginForm() to post the update. Well, this is breaking some pattern of coding in MVC or whatever good principle?
Retrieving data and filling in the input fields
$.ajax({
url: "../../Obra/" + id,
type: "POST",
success: function(data) {
var obj = JSON.parse(JSON.stringify(data));
tit.value = obj.titulo;
ed.value = obj.editora;
obj.autores.forEach(x => {
var newn = divAutor.appendChild(aut.cloneNode());
newn.value = x;
});
img.value = obj.imagem;
divAutor.removeChild(aut);
},
error: function() {
alert('Error.');
}
});
All modal:
<div class="modal" id="modalOverlay">
<div class="modal-content" id="modalContent">
<header class="modal-header">
<h1 id="updateObraModalTitulo"></h1>
</header>
#using(#Html.BeginForm("Update", "Obra", FormMethod.Post, new { id="form-update" })) {
<div class="updateObraDivProp">
#Html.LabelFor(m => m.Titulo, "Título:")
#Html.TextBoxFor(m => m.Titulo, new { #class="editInputValue", #id="editTituloInput" })
</div>
<div class="updateObraDivProp">
#Html.LabelFor(m => m.Editora, "Editora:")
#Html.TextBoxFor(m => m.Editora, new { #class="editInputValue", #id="editEditoraInput"})
</div>
<div class="updateObraDivProp">
#Html.LabelFor(m => m.Autores, "Autores:")
<div id="divInputAutores">
#Html.TextBoxFor(m => m.Autores, new { #class="inputPostValue", id="addAutoresInput"})
</div>
<div class="btnNewAutorOp">
<button type="button" id="btnAddAutor" onclick="addNewAutor()">+</button>
<button type="button" id="btnDeleteAutor" onclick="deleteNewAutor()">×</button>
</div>
</div>
<div class="updateObraDivProp">
#Html.LabelFor(m => m.Imagem, "Imagem:")
#Html.TextBoxFor(m => m.Imagem, new { #class="inputPostValue", #id="editImagemInput" })
</div>
<input type="submit">
}
</div>
</div>
Because I can't retrieve the Id property when I click in the modal with mvc (or maybe I can using partial views?), I'm using javascript to create a function with the param id and getting data with ajax and finally updating with form

Related

Passing and handling of varibles to a function with AJAX in MVC

I'm having trouble passing a variable into a function in my view. I'm fairly new to MVC and not sure how I save and pass information.
#model Models.Schedule.SheduleModel
#{
Layout = null;
}
<div>
<div class="tableRow">
<p>Make a schedule reminder.</p>
</div>
<div class="tableRow tableRowHeading">
<div class="row" style="width: 210px">Name</div>
<div class="row" style="width: 210px">Number</div>
</div>
#foreach (var shedule in Model.ScheduleList)
{
<div class="tableRow">
#using (Html.BeginForm("UpdateSchedule", "Schedule", FormMethod.Post))
{
<div class="cell" style="width: 210px">
#Html.HiddenFor(model => schedule.Id)
#Html.TextBoxFor(model => schedule.Name, new { #class = "inputFieldText" })
#Html.ValidationMessageFor(model => schedule.Name)
</div>
<div class="cell" style="width: 210px">
#Html.TextBoxFor(model => agent.ContactNumber, new { #class = "inputFieldText" })
#Html.ValidationMessageFor(model => agent.ContactNumber)
</div>
<div class="cell">
<button name="Update" type="submit" value="Update" class="button" title="Update details">
<span class="text">Update</span>
</button>
</div>
<div class="cell">
<button class="button" type="button" onclick="deleteFromSchedule();" value="Delete">
<span class="text">Delete</span>
</button>
</div>
}
</div>
}
</div>
#Scripts.Render("~/bundles/jqueryval")
<script>
function deleteFromSchedule() {
$.ajax(
{
type: 'POST',
url: urlBase + 'Schedule/UpdateSchedule/' + Id,
data:
{
Id: Id
},
success: function (data) {
console.log(data);
},
error: function () {
var errorMessage = 'Error occurred while sending message';
console.log(errorMessage);
}
});
}
}
</script>
I'm trying to pass the schedule Id in HiddenFor into the delete function but everything I try doesn't work, i'm also curious on how to handle the information gotten from the text box in a later unwritten div, I'd like to produce text on the screen saying
User #Model.Name and number #Model.Number will be notified of schedule change but I keep displaying blank spaces. an I use the form I'm creating for this information, what would the syntax be?. My method in the schedule controller is very straight forward.
[HttpPost]
public void UpdateSchedule(int Id)
{
////do stuff here
}
The simplest way is to add your id from the schedule into the inline function call (using razor), and add an id param into your javascript delete function:
<div class="cell">
<button class="button" type="button" onclick="deleteFromSchedule(#schedule.Id);" value="Delete">
<span class="text">Delete</span>
</button>
</div>
<script>
function deleteFromSchedule(id) {
$.ajax(
{
type: 'POST',
url: urlBase + 'Schedule/UpdateSchedule/' + id,
data:
{
Id: id
},
success: function (data) {
console.log(data);
},
error: function () {
var errorMessage = 'Error occurred while sending message';
console.log(errorMessage);
}
});
}
}
</script>

Ajax.BeginForm posts to surface controller and updates target id with full page instead of partial view

Have been trying to get a member profile management area working with ajax as each section of the page is hidden within a show hide div.
I have used ajax before in MVC applications but have never used it with umbraco surface controllers before. I'm unsure why returning a partial view in the controller is outputting the whole page and not just the partial view that I am giving to it.
Controller:
[HttpPost]
[ActionName("MvcMemberEditProfileDetails")]
public ActionResult MvcMemberEditProfileDetails(MvcMemberEditProfileDetailsModel model)
{
var memberService = Services.MemberService;
var currentUser = Membership.GetUser();
var member = memberService.GetByEmail(currentUser.Email);
bool result = false;
if (ModelState.IsValid)
{
...
}
if (result)
{
...
}
return PartialView("MvcMemberEditProfileDetails", model);
}
View:
#model Umbraco714.Models.MvcMemberEditProfileDetailsModel
#using (Ajax.BeginForm("MvcMemberEditProfileDetails", "MvcMember", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MvcMemberEditProfileDetails", InsertionMode = InsertionMode.Replace }))
{
if (Model.Result != null)
{
if (Model.Result == true)
{
<div id="result" class="alert alert-success">
#Html.Raw(Model.ResultMessage)
</div>
}
else
{
<div id="result" class="alert alert-danger">
#Html.Raw(Model.ResultMessage)
</div>
}
}
<div class="form-default">
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(m => m.FirstName)
#Html.TextBoxFor(m => m.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(m => m.LastName)
#Html.TextBoxFor(m => m.LastName)
#Html.ValidationMessageFor(m => m.LastName)
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(m => m.CompanyName)
#Html.TextBoxFor(m => m.CompanyName)
#Html.ValidationMessageFor(m => m.CompanyName)
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(m => m.CompanyPosition)
#Html.TextBoxFor(m => m.CompanyPosition)
#Html.ValidationMessageFor(m => m.CompanyPosition)
</div>
</div>
<div class="col-xs-12">
<div class="form-group">
#Html.LabelFor(m => m.CompanyBio)
<span class="bs-tooltip" data-toggle="tooltip" data-placement="top" title="Max 1000 characters long"><i class="fa fa-info-circle" aria-hidden="true"></i></span>
#Html.TextAreaFor(m => m.CompanyBio, new { #rows = "4", #maxlength = "1000" })
#Html.ValidationMessageFor(m => m.CompanyBio)
</div>
#TempData["Status"]
<div class="form-group nomargin">
<div class="text-right">
<button class="button" type="submit"><i class="fa fa-floppy-o" aria-hidden="true"></i> Update</button>
</div>
</div>
</div>
</div>
</div>
}
I have everything that needs to be included (as far as I'm aware) well before the form and there are no console errors.
<script src="/scripts/jquery.js"></script>
<script src="/scripts/bootstrap.min.js"></script>
<script src="/scripts/jquery-val.js"></script>
<script src="/scripts/jquery.unobtrusive-ajax.min.js"></script>
I have also made sure that UnobtrusiveJavaScriptEnabled is set to true in the web.config but I'm still getting a full page rendered when I post the form.
Initially:
When the page loads and the form shows
After:
When the form is submitted and the correct partial view is returned but inside of an entire
Feeling pretty dumbfounded that I've spent more that a couple of hours looking into this even though it's clearly working in a sort of way.
Is it possible / a known thing for this to happen? I searched around but couldn't find any topics with a similar issue, unless I was just wording things wrong.
Just looking for a nudge in the right direction if anybody has any ideas?
Umbraco can be funny with partials. Try returning CurrentUmbracoPage() in the controller.
As for the message, you could use TempData as it only lasts for one request, rather than the model.

Save the listbox selected items id into database

I want to pass list of ids into sql database in ASP MVC. In here there are two listbox where from one to other listbox able pass selected course names and then need to save those course ids with including the student id. How is this need to do using the jQuery? please help me on this. Here is my code upto now..
Create View
Create
.....
using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>StudentCourseVM</legend>
<div class="editor-label">
#Html.LabelFor(model => model.StudentId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.StudentId)
#Html.ValidationMessageFor(model => model.StudentId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StudentName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.StudentName)
#Html.ValidationMessageFor(model => model.StudentName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StudentAddress)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.StudentAddress)
#Html.ValidationMessageFor(model => model.StudentAddress)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CourseName)
</div>
<div class="editor-field">
<table>
<tr>
<td> Available Courses <br />
<select multiple="multiple" id="listboxCourse">
#foreach (var item in Model.courseList)
{
<option title="#item.CourseName" id="#item.CourseID">
#item.CourseName
</option>
}
</select>
</td>
<td>
<button type="button" id="btnAdd">Move Right>></button>
<br/>
<button type="button" id ="btnRemove">Move Left<<</button>
</td>
<td> Selected Courses<br />
<select multiple="multiple" id="addcourselist" >
</select>
</td>
</tr>
</table>
</div>
<p>
<input type="submit" value="Create" id="Create" />
</p>
</fieldset>
}
<script>
$(document).ready(function() {
$("#btnAdd").click(function() {
$("#listboxCourse > option:selected").appendTo("#addcourselist");
});
$("#btnRemove").click(function() {
$("#addcourselist > option:selected").appendTo("#listboxCourse");
});
})
$(function () {
$("#Create").click(function () {
var listCourse = new Array();
for (var i = 0; i < addcourselist.length ; i++) {
listCourse.push(Option[i].value);
}
});
$.ajax({
type: "POST",
data: listCourse,
dataType : "json",
url: "Student/Create",
success: function (data) {
alert("Code is running...............");
}
});
})
Controller
[HttpGet]
[ActionName("Create")]
public ActionResult Create()
{
StudentCourseVM studentcourse = new StudentCourseVM();
StudentBusinessLayer studentBusinessLayer = new StudentBusinessLayer();
List<Course> coursestudentList = studentBusinessLayer.CourseList.ToList();
studentcourse.courseList = coursestudentList;
return View(studentcourse);
}
[HttpPost]
[ActionName("Create")]
public ActionResult Create(StudentCourseVM studentcourse)
{
if (ModelState.IsValid)
{
StudentBusinessLayer studentBusinessLayer = new StudentBusinessLayer();
List<Course> coursestudentList = studentBusinessLayer.CourseList.ToList();
studentcourse.courseList = coursestudentList;
studentBusinessLayer.AddStudent(studentcourse);
return RedirectToAction("Index");
}
return View();
}
How am i supposed to do this. Two listbox are like this. The items in second listbox need to be saved in database with the relate studentid.
You can save it as JSON (objets) strings
Check out How To Populate Html.Listbox with Ajax result using mvc 4

How to stop page change on Ajax Form Posting in MVC Mobile

I am creating an application on MVC Mobile and having a problem. Here i have a Partial view load on a page run-time by ajax. In which i have a simple form which will submit with ajax request like bellow:
#model Test.Models.TestModel
#using (this.Ajax.BeginForm("Create", "Test", Model, new AjaxOptions { UpdateTargetId = "divResult", LoadingElementId = "loading", LoadingElementDuration = 2000, HttpMethod = "Post" }, new { id = "frmCreate" }))
{
#Html.AntiForgeryToken()
<div class="messageBox">#Html.Raw(TempData["Message"])</div>
<div class="atmForm">
<div class="control-group">
#Html.LabelFor(x => x.Name)
#Html.TextBoxFor(x => x.Name, new { #placeholder = "Name", #class = "inputStyle" }) #Html.ValidationMessageFor(x => x.Name)
</div>
<div class="control-group">
#Html.LabelFor(x => x.Notes)
#Html.TextAreaFor(x => x.Notes, new { #placeholder = "Notes", #class = "inputStyle" }) #Html.ValidationMessageFor(x => x.Notes)
</div>
</div>
<div class="form-actions2 clearfix">
<input type="submit" class="btn btn-block" value="Create" data-ajax="false" id="btnFormSubmit" />
</div>
}
<script type="text/javascript">
$.validator.unobtrusive.parse("#frmCreate");
</script>
The problem is when user submit the form the controller called twice. First time it return the partial view and then again it calls and then jQuery Mobile change the page. I am Using MVC4 with jQuery Mobile 1.1.0
(please note that create.cshtml (desktop ver) works fine but create.Mobile.cshtml (mobility ver) havng this problem)
Do not submit the form, use $("#myForm").serialize() as ajax data.

return 2 values to controller, text remains NULL

trying to pass 2 values back to the controller id', and 'text'...id passes ok but text always returns nulll any idea why?
<div class="modal-body">
<input type="hidden" id="AlertFreeTextId" name="AlertFreeTextId" value="#Model.AlertFreeTextId" />
<input type="hidden" id="Text" name="Text" value="#Model.Text" />
<div class="form-group">
#Html.LabelFor(x => x.Text)
#Html.TextAreaFor(x => x.Text, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.Text)
</div>
<div>
<a href='#Url.Action("CreateAlertFreeText", "AlertFreeText", new { id = Model.AlertFreeTextId, text = Model.Text})'>
<button class="btn btn-primary">#T("Save")</button>
</a>
</div>
</div>
//controller
public ActionResult CreateAlertFreeText(int id, string text)
{
}
This line here:
<a href='#Url.Action("CreateAlertFreeText", "AlertFreeText", new { id = Model.AlertFreeTextId, text = Model.Text})'>
All this is doing is getting the text that was passed into the View. I assume when you call the view, Model.Text is null, so that's exactly what it's returning.
You need to pull the data from the form when you submit like that.
I'd suggest creating either using a form post, or calling a jquery method to do the post where you can pull the form data.
Maybe something like this: (warning: untested!)
<div class="modal-body">
<input type="hidden" id="AlertFreeTextId" name="AlertFreeTextId" value="#Model.AlertFreeTextId" />
<input type="hidden" id="Text" name="Text" value="#Model.Text" />
<div class="form-group">
#Html.LabelFor(x => x.Text)
#Html.TextAreaFor(x => x.Text, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.Text)
</div>
<div>
<a href='#' id='alertFreeTextLink'>
<button class="btn btn-primary">#T("Save")</button>
</a>
</div>
</div>
<script>
$(document).ready(function() {
$("#alertFreeTextLink").click(function() {
var url = '#Url.Action("CreateAlertFreeText", "AlertFreeText",
new { id = Model.AlertFreeTextId })';
url = url + "&text=" + $("#Text").val();
$.ajax({
url: url
})
.done(function(response) {
/// Do something here
});
});
});
</script>

Categories