In this article I will show you how to modify xml file using asp.net c# mvc. I have xml file with column fields such as id, paragraph, link etc.
I created class file for xml column fields.
public class homecontent
{
private string mId;
private string mHeading;
private string mParagraph;
private string mParagraph2;
private string mLink;
public string Id
{
get { return mId; }
set { mId = value; }
}
public string Heading
{
get { return mHeading; }
set { mHeading = value; }
}
public string Paragraph
{
get { return mParagraph; }
set { mParagraph = value; }
}
public string Paragraph2
{
get { return mParagraph2; }
set { mParagraph2 = value; }
}
public string Link
{
get { return mLink; }
set { mLink = value; }
}
}
View page:
<div class="control-group">
<span class="custom-name-field">heading </span><span style="width: 200px">
<input type="text" id="txtHeading" />
<input type="hidden" id="hfdTextId" />
</span>
</div>
<div class="control-group">
<span class="custom-name-field">paragraph </span><span style="width: 200px">
<textarea cols="3" rows="3" id="txtparagraph" ></textarea>
</span>
</div>
<div class="control-group">
<span class="custom-name-field">paragraph2 </span><span style="width: 200px">
<textarea cols="3" rows="3" id="txtparagraph2" ></textarea>
</span>
</div>
<div class="control-group">
<span class="custom-name-field">Link </span><span style="width: 200px">
<input type="text" id="txtLink" />
</span>
</div>
<div id="divProgressText" class="prog" style="display: none; text-align: center">
<img src="img/spinner.gif" height="30" width="30" align="middle" />
</div>
<div class="modal-footer">
<button class="btn btn-primary" aria-hidden="true" id="btnSaveText" onclick="javascript:returnSaveText();">
Save</button>
<button class="btn" id="btnCancelText" data-dismiss="modal">
Cancel</button>
</div>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function SaveText() {
var dataObject = { Id: $("#hfdTextId").val(), Heading: $("#txtHeading").val(), Paragraph: $("#txtparagraph").val(), Paragraph2: $("#txtparagraph2").val(), Link: $("#txtLink").val() };
dataObject =JSON.stringify(dataObject);
$.ajax({
url: '@Url.Action("Index", "Home", new { area = "Admin" })',
type: 'POST',
data: dataObject,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
$('#myModal').modal('hide');
// BindGrid();
$('.errorBlock').html(response);
$('.errorBlock').show();
},
error: function (xhr, ajaxOptions,thrownError) {
$(".errorBlockMain").html(xhr.responseText);
$(".errorBlockMain").show();
$('.prog').hide();
}
});
}
function openText(Id) {
$(".errorBlock").hide();
$.ajax({
type: 'POST',
url: '@Url.Action("EditText", "Home", new { area = "Admin" })',
data: "{'Id' : " + Id + "}",
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (response) {
$('#myModalText').modal('show');
$("#hfdTextId").val(response.Id);
$("#txtHeading").val(response.Heading);
$("#txtparagraph").val(response.Paragraph);
$("#txtparagraph2").val(response.Paragraph2);
$("#txtLink").val(response.Link);
},
error: function (xhr, ajaxOptions,thrownError) {
$(".errorBlock").html(xhr.responseText);
$(".errorBlock").show();
}
});
}
</script>
Home Controller:
[HttpPost]
public ActionResult Index(homecontent homecontent)
{
string message = "";
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("~/Areas/Admin/xmlData/Home.xml"));
var rowsToUpdate = ds.Tables[0].AsEnumerable().Where(r =>r.Field<string>("Id") ==homecontent.Id);
foreach (var row in rowsToUpdate)
{
row.SetField("heading",homecontent.Heading);
row.SetField("paragraph",homecontent.Paragraph);
row.SetField("paragraph2",homecontent.Paragraph2);
row.SetField("link",homecontent.Link);
message = "Record updated Successfully.";
}
ds.WriteXml(Server.MapPath("~/Areas/Admin/xmlData/Home.xml"));
if (Request.IsAjaxRequest())
{
return Json(message, JsonRequestBehavior.AllowGet);
}
else
{
return RedirectToAction("Index", "Home", new { area = "Admin" });
}
}
[HttpPost]
public ActionResult EditText(string Id)
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("~/Areas/Admin/xmlData/Home.xml"));
IEnumerable<DataRow> rowDetails = from DataRow row in ds.Tables[0].Rows
where row.Field<string>(0) == Id
select row;
homecontent homecontent=new homecontent();
homecontent.Id=Convert.ToString(rowDetails.ElementAt(0).ItemArray[0]);
homecontent.Heading = Convert.ToString(rowDetails.ElementAt(0).ItemArray[1]);
homecontent.Paragraph = Convert.ToString(rowDetails.ElementAt(0).ItemArray[2]);
homecontent.Paragraph2 = Convert.ToString(rowDetails.ElementAt(0).ItemArray[3]);
homecontent.Link = Convert.ToString(rowDetails.ElementAt(0).ItemArray[4]);
if (Request.IsAjaxRequest())
{
return Json(homecontent, JsonRequestBehavior.AllowGet);
}
else
{
return RedirectToAction("Index", "Home", new { area = "Admin" });
}
}
Description:
When you edit the record by clicking the save button, the controller receives the objects. You can identify which record to update xml file by finding the record using the linq by column id.
Output (Records updated):
Post your comments / questions
Recent Article
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
- The request was aborted: Could not create SSL/TLS secure channel -Error in Asp.net
- FieldError: Cannot resolve keyword 'id' into field in Django project
Related Article